JavaScript Tutorial

Exception Handling

Exception handling is a method used to handle abnormal statements in code and control the flow of the program.

Different handlers are employed to process exceptions and execute the code. For instance, dividing a non-zero value by zero would result in infinity, which is an exception. Exception handling allows us to execute and handle such cases.

To raise an exception, we use the throw statement. It means that when an abnormal condition occurs, an exception is thrown using throw.

The thrown exception is handled by enclosing the code in a try...catch block. If an error is encountered, the catch block will execute; otherwise, only the statements in the try block will be executed.

Types of errors

While coding, there are three types of errors that can occur:

  1. Syntax Error: A syntax error may appear when a user makes a mistake in the predefined syntax of a programming language.

  2. Runtime Error: A runtime error occurs during program execution. These errors are known as exceptions, and exception handlers are used to handle them.

  3. Logical Error: A logical error happens when there is a mistake in the program's logic, leading to undesired output or abnormal termination.

Javascript try…catch

The try...catch statement is commonly used in various programming languages, including JavaScript. It is used to handle error-prone sections of code.

The try block is where the code that needs error testing is placed. If an error occurs, it is passed to the catch block, where appropriate actions are taken to handle the error. If no error occurs, the code within the try block is executed.

The catch block is responsible for handling errors by executing a set of statements. It can contain either a user-defined exception handler or a built-in handler. The catch block is only executed when there is an error to be handled in the try block; otherwise, it is skipped.

Syntax:-

Throw statements are used to throw user-defined errors. Users can define and throw their own custom errors. When a throw statement is executed, the statements following it are not executed, and the control is transferred directly to the catch block.

Input:-

Output:-


Go back to Previous Course