Error handling is crucial in JavaScript to gracefully handle unexpected situations and prevent our code from crashing.
JavaScript provides several mechanisms for error handling, and the most common one is using the try...catch statement.
try { // Code that might throw an exception throw new Error("This is a custom error message"); } catch (error) { // Handle the error console.error("An error occurred:", error.message); } finally { // Optional: Code that will be executed regardless of whether an error occurred or not console.log("This will always be executed"); }
The try block contains the code that might throw an exception.
If an exception occurs, the control is transferred to the catch block, where we can handle the error.
The error object contains information about the error, such as the error message "error.message".
The finally block is optional and contains code that will be executed regardless of whether an error occurred or not. It's often used for cleanup operations.
We can also catch specific types of errors using multiple catch blocks:
try { // Code that might throw different types of exceptions } catch (error) { if (error instanceof TypeError) { console.error("TypeError occurred:", error.message); } else if (error instanceof RangeError) { console.error("RangeError occurred:", error.message); } else { console.error("An unexpected error occurred:", error.message); } } finally { // Cleanup code }
Apart from try...catch, there are other mechanisms for error handling:
function divide(a, b) { if (b === 0) { throw new Error("Division by zero is not allowed"); } return a / b; } try { console.log(divide(10, 2)); console.log(divide(5, 0)); } catch (error) { console.error("An error occurred:", error.message); }
We can use the throw statement to throw custom errors.
somePromiseFunction() .then(result => console.log(result)) .catch(error => console.error("An error occurred:", error.message));
async function fetchData() { try { let response = await fetch('https://api.example.com/data'); let data = await response.json(); console.log(data); } catch (error) { console.error("An error occurred:", error.message); } } fetchData();
When working with promises, we can use the ".catch()" method to handle errors.
When using async/await, we can use try...catch for error handling.