Error Handling in JavaScript
Error handling allows JavaScript programs to detect, handle and respond to errors without unexpectedly stopping the application.
What is Error Handling?
Errors can occur while a JavaScript program is running. Error handling provides a way to manage these errors.
JavaScript commonly uses try, catch, finally and throw for error handling.
Simple Definition
Error handling is the process of detecting and handling errors in a JavaScript program.
The catch block handles an error generated inside the try block.
try...catch
The try block contains code that may generate an error.
The catch block executes when an error occurs inside the try block.
Example 1: Basic try...catch
try {
console.log("Starting program");
throw new Error("Something went wrong");
}
catch (error) {
console.log("Error handled");
}
Starting program
Error handled
Example 2: Using Error Object
The catch block receives an error object. We can use its message property to display information about the error.
try {
throw new Error("Invalid operation");
}
catch (error) {
console.log(error.message);
}
Invalid operation
Example 3: try...catch...finally
The finally block executes whether an error occurs or not.
try {
console.log("Try block executed");
}
catch (error) {
console.log("Error occurred");
}
finally {
console.log("Finally block executed");
}
Try block executed
Finally block executed
Important Points
• try contains code that may generate an error.
• catch handles the error.
• finally executes after try/catch processing.
• throw can be used to create a custom error.
• Error handling helps make applications more reliable and easier to debug.
Summary
JavaScript provides try, catch, finally and throw to handle errors. Proper error handling prevents unexpected application failures and makes JavaScript programs more reliable.