Learn JavaScript
Lesson 1 - Introduction To JavaScript
Lesson 2 - Basic JavaScript Syntax
Lesson 3 - Control Flow
Lesson 4 - Functions
Lesson 5 - Basic Data Structures
Lesson 6 - Basic String Operations
Lesson 7 - Basic Array Operations
Lesson 9 - Packages
Lesson 10 - User Input
JavaScript handles exceptions using try
, catch
, and finally
blocks.
Where:
try
block contains the code that might throw an exception.catch
block is used to handle the exception if one occurs.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.