Exception handling is the a of responding to unexpected events during the execution of a computer program. This ensures that the program runs smoothly.
Let’s discuss the role of the try
-catch
statement in exception handling.
try
-catch
blocktry
: The program will run the code block that follows this statement and does one of the following:
try
block and executes the code in the catch
block to handle this exception.catch
block and executes the code that comes after the catch
block (sequential execution).catch
: The code block that follows this statement handles the error/exception thrown by the try
block and responds appropriately without crashing the program.
In JavaScript, we can add a throw
or a finally
clause with these statements.
throw
: This statement is used within the try
block. We can use these statements to write the errors. For example, if we expect multiple types of errors in the try
block, we can handle all these errors differently by using throw
statements.
finally
: The code in this block will run after the try
and/or catch
blocks have completed their execution.
Now that we know what each statement does and its use, let’s look at the syntax below:
try{// Code to test for error comes herethrow new Error ("some error") // We can make our own errors and handle them in the catch block}catch(error){//Code to handle error comes here}finally{//Code to be executed after the code in try and/or catch blocks is executed}
Let’s look at a few examples of exception handling in JavaScript using the try
, catch
, throw
, and finally
statements.
try
-catch
statementIn the example below, we will deliberately write a statement giving an error in the try
block to show how it works.
Then, we will log the error to the console in the catch
block:
try{addAlert()}catch(error){console.log(error)}console.log("\nEnd of try-catch block")
try
block:
Line 2: We call the addAlert()
method. This will throw an exception as we haven't declared this function.
catch
block:
Line 6: We display the error
on the console.
Outside try-catch block:
Line 9: We display the message End of try-catch block
on the console. This statement will be executed after the try-catch block.
try
, throw
, and catch
statementsThe example below shows how we can create our error using a throw
statement. It also shows how we can create different errors and how to handle them differently in the catch
block.
try{// you can change this number to see how the try-catch block works with throw statementsnumber = 5if(number == 2)throw new Error ('This is the wrong input')else if(number == 5)throw new Error ('Try again')}catch(err){if(err.message == 'This is the wrong input'){// we can write code to handle this error hereconsole.log(err.message)}else if(err.message == 'Try again') {// we can write code to handle this error hereconsole.log(err.message)}}console.log("End of try-catch block")
Note: We can obtain our error message by accessing the
message
attribute of theError
object.
try
block:
Line 3: We initialize the value of number
to 5
.
Lines 5-8: We throw
the errors based on the value of number
. In our case the value of number
is 5
so we throw
the error with the message Try again
.
catch
block:
Lines 12-20: We identify our error using err.message
and print the error
's message
on the console. In our case the err.message
is Try again
.
Outside try-catch block:
Lines 23: We display the message End of try-catch block
on the console. This statement will be executed after the execution of the try-catch block.
try
, catch
, throw
, and finally
togetherThis last example shows the use of the finally
statement with the other three statements.
We throw an exception using the throw
statement in the try
block. Then, the program executes the catch
block and the finally
block in the end:
try{console.log("This statement works")throw new Error('This statement throws an error')}catch(error){console.log("Error has been handled")}finally{console.log("Everything has been handled")}
try
block:
Line 2: We display the message This statement works
on the console.
Line 3: We throw
our own error that says This statement throws an new error
. This error will be caught in the catch
block.
catch
block:
Line 6: We display the message Error has been handled
on the console.
finally
block:
Line 9: We display the message Everything has been handled
on the console. This will be executed in the end after the execution of try-catch blocks.
It is important for us to know how to use try
-catch
, finally
and throw
statements in JavaScript to handle our program's errors more efficiently. In this way, we can handle the errors on our own without facing any program crashes.
Free Resources