JavaScript Errors
JavaScript Errors - Throw and Try to Catch
Section titled “JavaScript Errors - Throw and Try to Catch”The try statement allows you to test a block of code for potential errors during its execution.
The catch statement allows you to define a block of code to be executed if an error occurs in the try block.
The throw statement allows you to create custom errors. It’s best practice to throw Error objects.
The finally statement allows you to execute code after try and catch, regardless of whether an error occurred or was caught.
Errors Will Happen!
Section titled “Errors Will Happen!”When executing JavaScript code, various errors can occur. These can be syntax errors, runtime errors, or logical errors.
Errors can stem from programmer mistakes, invalid user input, network issues, or other unexpected situations:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Error Handling Example</title></head><body> <p id="demo"></p> <script> try { // Intentionally causing a ReferenceError: nonExistentFunction is not defined nonExistentFunction("Welcome guest!"); } catch (error) { const demoElement = document.getElementById("demo"); // It's good practice to display error.message. You can also log error.name or the full error object. demoElement.textContent = `Caught an error: ${error.message}`; console.error(error); // Also log the full error to the console for debugging } </script></body></html>In the example above, we tried to call a function that doesn’t exist, causing a ReferenceError.
The catch block ‘catches’ this error, and executes code to handle it, like displaying a user-friendly message.
JavaScript try and catch
Section titled “JavaScript try and catch”The try statement defines a block of code to be monitored for errors.
The catch statement defines a block of code to be executed if an error occurs within the try block. The catch block receives an error object (often named err or error) containing details about the error (e.g., error.name, error.message).
The try and catch statements come in pairs:
try { // Block of code to try} catch (error) { // Block of code to handle errors // 'error' is an Error object}Common error types include Error, SyntaxError, ReferenceError, TypeError, RangeError, and URIError. You can check error.name or error instanceof TypeError to handle specific errors differently.
JavaScript Throws Errors
Section titled “JavaScript Throws Errors”When a runtime error occurs, JavaScript will normally stop execution and ‘throw’ an error object.
If an error is thrown and not caught by a try...catch block, the script will terminate (or in browsers, the current execution path will stop, and an error will be logged to the console).
The throw Statement
Section titled “The throw Statement”The throw statement allows you to create and throw your own custom errors.
This is technically referred to as ‘throwing an exception’.
While you can throw any value (like a string or number), it is strongly recommended to throw Error objects or objects inheriting from Error. This provides more consistent error information (like stack traces).
// Old way (avoid):// throw "Too big";// throw 500;
// Modern best practice:throw new Error("Something went wrong!");throw new TypeError("Invalid type provided.");
// For more specific errors, you can create custom error classes:class NetworkError extends Error { constructor(message) { super(message); this.name = "NetworkError"; }}// throw new NetworkError("Connection failed.");Using throw with try and catch allows you to manage program flow and provide meaningful error messages or recovery logic.
Input Validation Example
Section titled “Input Validation Example”This example demonstrates validating user input. If the input is invalid, an Error object is thrown and caught.
The catch block then displays a custom error message based on the error thrown:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Input Validation</title></head><body> <p>Please input a number between 5 and 10:</p> <input id="valueInput" type="text" /> <!-- Changed to type="text" for broader validation demo --> <button type="button" onclick="validateInput()">Test Input</button> <p id="messageArea"></p>
<script> function validateInput() { const messageElement = document.getElementById("messageArea"); const inputElement = document.getElementById("valueInput"); messageElement.textContent = ""; // Clear previous messages
try { const inputValue = inputElement.value.trim();
if (inputValue === "") { throw new Error("Input cannot be empty."); }
const number = Number(inputValue);
if (isNaN(number)) { throw new Error("Input is not a valid number."); }
if (number < 5) { throw new Error("Value is too low. Minimum is 5."); }
if (number > 10) { throw new Error("Value is too high. Maximum is 10."); }
messageElement.textContent = "Input is valid!"; } catch (error) { messageElement.textContent = `Error: ${error.message}`; console.error("Validation failed:", error); } } </script></body></html>Note: HTML5 input attributes like type="number", min, max, and required provide built-in browser validation. JavaScript validation complements this for more complex rules or better user feedback.
The finally Statement
Section titled “The finally Statement”The finally statement defines a block of code that will execute after the try and catch blocks, regardless of whether an error occurred or was caught.
This is useful for cleanup tasks, such as closing files, releasing resources, or resetting states.
try { // Block of code to try} catch (error) { // Block of code to handle errors} finally { // Block of code to be executed regardless of the try/catch result}Example demonstrating finally:
function processData() { const inputElement = document.getElementById("valueInput"); // Assuming it exists from previous example const messageElement = document.getElementById("messageArea"); let result = "Processing completed.";
try { messageElement.textContent = "Attempting to process..."; const value = parseInt(inputElement.value, 10);
if (isNaN(value)) { throw new Error("Cannot process non-numeric input."); } if (value < 0) { throw new Error("Cannot process negative values."); } // Simulate processing result = `Processed value: ${value * 2}`; messageElement.textContent = result;
} catch (error) { messageElement.textContent = `Error during processing: ${error.message}`; result = "Processing failed."; // Update result based on error } finally { // This block always executes console.log("Cleanup phase: Operation finished. Result: " + result); // Example: inputElement.value = ""; // Clear input field after attempt }}// To test, call processData() after user input. Ensure HTML elements exist.For more advanced error handling, especially with asynchronous operations, explore Promises and async/await which have their own error handling mechanisms (.catch() for Promises, try/catch for async/await).
Further reading: MDN: try…catch