JavaScript Try Catch - Handling Exception
About JavaScript Error Handling
In JavaScript, error handling helps to manage exceptions (errors) that occur during code execution.
It allows the programmers to gracefully manage errors and prevent application from being crashed.
The primary way to handle errors is using the try...catch statement.
Using Try...Catch Statement
Components of Try...Catch Statement
try : The code that might throw an exception is placed inside the try block.
catch : If an exception occurs within the try block, the execution of the code is immediately stopped and program flow jumps to the
finally : This is optional. This block always executes after the try and catch blocks, regardless of the outcome. It is useful for cleanup tasks.
Example of Try...Catch Statement
Output of the above example
An error occurred: Failed to fetch
Execution completed.
Explanation of The Code
-
try {...}: This is the try block. -
let response = await fetch("https://invalidurl.com"): This line of code in the try block will throw an exception(error) as the url is invalid. As an error occurs in the try block, control immediately jumps to the catch block. -
catch (error) {...}: This is the catch block. -
console.log("An error occurred:", error.message): The codeerror.messageprovides a human-readable message describing the error issue. -
finally{...}: The finally block always executes regardless of the error or outcome.
Properties of Error Object
Each error object contains certain properties that provide detailed information about the error.
Example of Error Object
Output of the above example
ReferenceError
twenty is not defined
ReferenceError: twenty is not defined at <anonymous> :3:23
JavaScript Compiler For Live Practice
Practice the above JavaScript code in the following JavaScript Editor. Create more try...catch statements in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.
JavaScript Editor