Error Handling
Error handling in JavaScript involves identifying and managing errors that occur during the execution of a program to prevent crashes and handle exceptional situations gracefully. JavaScript provides various mechanisms for error handling, including try...catch statements, throwing and catching exceptions, and handling asynchronous errors.
try...catch:
By containing the code that can result in an error within a try block, the try...catch statement enables you to handle synchronous/asynchronous problems. The matching catch block is invoked whenever an error arises inside the try block, enabling you to gently address the error.
try { // Code that might throw an error } catch (error) { // Error handling logic }
Here's an example:
try { const result = 10 / 0; // Division by zero console.log(result); } catch (error) { console.error("An error occurred:", error); }
In this example, the catch block will execute since dividing by zero throws an error. The error object provides information about the error, such as its type and message.
Throwing Exceptions:
The keyword throw can be used to manually throw exceptions. You can create your own unique error conditions and manage them by throwing an exception by using try...catch blocks or allowing them to propagate up the call stack.
throw new Error("Some specific Custom error message");
Handling Asynchronous Errors:
Some errors occur during API requests or setInterval/setTimeout callback methods and that can be handled in a different way.
Asynchronous approaches such as Promises and async/await have their own way to handle errors.
The .catch() method of Promises can be used to handle errors:
asyncFunction() .then(result => { // Code for successful completion }) .catch(error => { // Error handling logic });
Try...catch can be used with async/await to manage asynchronous errors:
async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); // Code for successful completion } catch (error) { // Error handling logic } }
In the above example, any error occurring within the try block, such as network errors(API request error) or JSON parsing errors, will be caught in the catch block.