Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 8 - Exception Handling

8.2 Handling Exceptions

JavaScript handles exceptions using try, catch, and finally blocks.

Where:

  • The try block contains the code that might throw an exception.
  • The catch block is used to handle the exception if one occurs.
  • The finally block is executed regardless of whether an exception is thrown or not. It allows you to put some code that needs to be run even if an error has occurred, helping your program to continue some tasks when your program encounters an error.

Follow the example below:

try {
    let result = a + 5;
    console.log(result);
} catch (error) {
    console.log("An error occurred:", error.message);
} finally {
    console.log("Finally block executed.");
}

Here, the variable a is undefined (doesn't have any value). This will generate an error that we displayed via the catch block. The finally block will execute even if the program doesn't have any errors.

Now, try to provide a valid number like 10 instead of a. You'll notice that the finally block will also be executed this time.