Exception handling in JavaScript allows you to manage and respond to errors in your code gracefully. It helps prevent your application from crashing and provides meaningful feedback to users when something goes wrong.
Key Components of Exception Handling
try
block: Contains code that might throw an error.catch
block: Contains code that executes if an error occurs in thetry
block.finally
block: Contains code that executes after thetry
andcatch
blocks, regardless of whether an error occurred.throw
statement: Manually triggers an exception.
Basic Syntax
try { // Code that may throw an error } catch (error) { // Code to handle the error } finally { // Code that will run after try/catch }
1. try
and catch
Example
try { let result = 10 / 0; console.log(result); // Outputs: Infinity } catch (error) { console.log("An error occurred: " + error.message); }
In this example, there’s no error in dividing by zero in JavaScript, so the catch
block is not executed. However, the try-catch
structure is used for any unexpected errors.
2. Handling Specific Errors
try { let x = y + 1; // ReferenceError because y is not defined } catch (error) { console.log("Error: " + error.name + " - " + error.message); }
Output:
Error: ReferenceError - y is not defined
3. Using finally
The finally
block is executed after the try
and catch
blocks, no matter what.
try { let x = 5 / 0; } catch (error) { console.log("Error: " + error.message); } finally { console.log("This will run regardless of the error."); }
4. throw
Statement
You can throw your own custom errors using the throw
statement.
function checkNumber(num) { if (num < 0) { throw new Error("Number cannot be negative"); } return num; } try { console.log(checkNumber(-5)); } catch (error) { console.log("Error: " + error.message); }
Output:
Error: Number cannot be negative
5. Custom Error Types
You can create custom error types by extending the Error
class.
class CustomError extends Error { constructor(message) { super(message); this.name = "CustomError"; } } try { throw new CustomError("This is a custom error"); } catch (error) { console.log(error.name + ": " + error.message); }
6. Nested try-catch
You can nest try-catch
blocks to handle different errors separately.
try { try { let x = undefinedVariable; // This will throw ReferenceError } catch (error) { console.log("Inner catch: " + error.message); } let y = 1 / 0; // No error in JavaScript, result is Infinity } catch (error) { console.log("Outer catch: " + error.message); }
7. Using finally
with Asynchronous Code
When dealing with asynchronous code, make sure the finally
block executes properly.
async function fetchData() { try { let response = await fetch("https://api.example.com/data"); let data = await response.json(); console.log(data); } catch (error) { console.log("Error fetching data: " + error.message); } finally { console.log("Cleanup tasks"); } } fetchData();
Summary of Exception Handling in JavaScript
try-catch
: Catches errors and allows you to handle them gracefully.finally
: Executes code aftertry
andcatch
, regardless of the outcome.throw
: Manually throw exceptions to handle specific error scenarios.- Custom Errors: Extend the
Error
class to create more meaningful and specific errors.
Exception handling is essential for robust and user-friendly applications, ensuring errors are handled gracefully without crashing the application.