Exception handling in JavaScript is crucial for managing errors that arise during the execution of code. It allows developers to handle anomalies gracefully and maintain the normal flow of the program. Here’s a breakdown of how exception handling works in JavaScript:
Exception handling is a method used to handle errors or exceptional conditions that occur during the execution of a program. Instead of the program terminating abruptly when an error occurs, exception handling allows for a structured way to handle these errors and recover from them.
1. Syntax Error: Mistakes in the syntax of the programming language. These errors are detected at compile time and prevent the code from running.
Example: Missing a parenthesis or semicolon.
Runtime Error: Errors that occur during the execution of the program. These are also known as exceptions.
Example: Dividing a number by zero.
Logical Error: Errors in the logic of the code that produce incorrect results or behavior.
Example: Using incorrect formulae or logic in calculations.
When an exception occurs, JavaScript creates an Error object. This object can be used to understand and manage the error. The Error object has two primary properties:
• name: The name of the error type (e.g., "TypeError").
• message: A description of the error.
JavaScript provides several built-in error types, including:
• EvalError: Errors related to the eval() function.
• InternalError: Internal errors thrown by the JavaScript engine.
• RangeError: Errors when numeric values are out of range.
• ReferenceError: Errors for invalid references.
• SyntaxError: Errors in syntax.
• TypeError: Errors related to data types.
• URIError: Errors related to URI manipulation functions.
JavaScript provides several statements for handling exceptions:
Used to manually throw an exception.
throw new Error("Error message");
Used to catch exceptions that occur in the try block.
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
console.error(error.message);
}
Includes a finally block that executes after the try and catch blocks, regardless of whether an exception was thrown or not.
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
console.error(error.message);
} finally {
// Code that always executes
console.log("Cleanup code");
}
<script>
function divideNumbers(a, b) {
try {
if (b === 0) {
throw
new Error("Division by zero is not allowed.");
}
return a / b;
}
catch (error) {
// Display error message on the webpage
document.write("<p>Error: " + error.message +
"</p>");
return null; // Return a fallback value
}
finally {
// Display completion message on the webpage
document.write("<p>Execution
completed.</p>");
}
}
// Test the function and display results on the webpage
document.write("<p>10 divided by 0 is: " + divideNumbers(10, 0) +
"</p>"); // Outputs: Error message and null
</script>
Error: Division by zero is not allowed.
Execution completed.
10 divided by 0 is: null