CARVIEW |
How to use try-catch statements in JavaScript
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.
The try
-catch
block
-
try
: The program will run the code block that follows this statement and does one of the following:- If the code throws an error/exception, it stops the execution in the
try
block and executes the code in thecatch
block to handle this exception. - If the code executes without any errors, it skips the
catch
block and executes the code that comes after thecatch
block (sequential execution).
- If the code throws an error/exception, it stops the execution in the
-
catch
: The code block that follows this statement handles the error/exception thrown by thetry
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 thetry
block. We can use these statements to write the errors. For example, if we expect multiple types of errors in thetry
block, we can handle all these errors differently by usingthrow
statements. -
finally
: The code in this block will run after thetry
and/orcatch
blocks have completed their execution.
Syntax
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}
Examples
Let’s look at a few examples of exception handling in JavaScript using the try
, catch
, throw
, and finally
statements.
Using a simple try
-catch
statement
In 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")
Explanation
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.
Using the try
, throw
, and catch
statements
The 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.
Explanation
try
block:
Line 3: We initialize the value of
number
to5
.Lines 5-8: We
throw
the errors based on the value ofnumber
. In our case the value ofnumber
is5
so wethrow
the error with the messageTry again
.
catch
block:
Lines 12-20: We identify our error using
err.message
and print theerror
'smessage
on the console. In our case theerr.message
isTry 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.
Using try
, catch
, throw
, and finally
together
This 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")}
Explanation
try
block:
Line 2: We display the message
This statement works
on the console.Line 3: We
throw
our own error that saysThis statement throws an new error
. This error will be caught in thecatch
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.
Conclusion
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.
Relevant Answers
Explore Courses
Free Resources