When handling exceptions in JavaScript, we typically use several methods to ensure code robustness and effective error handling.
1. try...catch Statement
This is the most common approach for handling runtime errors. The try block contains code that may throw errors, while the catch block captures these errors, enabling developers to handle them.
Example Code:
javascripttry { // Code that may throw an exception const x = y + 1; // If y is undefined, this will throw an exception } catch (error) { // Error handling console.error("Captured error: ", error.message); }
2. finally Statement
Often used with try...catch. Regardless of whether the try block executes successfully, the finally block runs, typically for cleanup or resource release.
Example Code:
javascripttry { // Code that may throw an exception } catch (error) { // Error handling console.error("Error message", error); } finally { // Runs regardless of success or failure console.log("Cleanup completed"); }
3. throw Keyword
Using the throw keyword allows developers to manually throw exceptions, enabling custom error generation at any point during execution.
Example Code:
javascriptfunction checkNumber(num) { if (isNaN(num)) { throw new Error("Input value is not a number"); } return true; } try { checkNumber('test'); } catch (error) { console.error(error.message); }
4. Error Handling with Promises
For asynchronous operations, Promises provide the .catch() method to capture exceptions that occur during these operations.
Example Code:
javascriptfetch('https://api.example.com/data') .then(response => response.json()) .catch(error => console.error('Error occurred: ', error));
5. Using Async/Await with try...catch
When using async and await (introduced in ES8) for asynchronous programming, you can directly apply try...catch within this syntax to handle exceptions.
Example Code:
javascriptasync function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Request failed: ', error); } }
By employing these methods, we can effectively manage various errors and exceptions during JavaScript execution, thereby enhancing program stability and user experience.