Week 11: Handling Errors and Debugging Code
Learn how to anticipate, catch, and fix errors in your JavaScript programs.
Explore Chapter 11Exception Handling using try...catch...finally.
JavaScript provides the try...catch...finally statement to handle runtime errors (exceptions) gracefully, preventing them from crashing your entire script.
Syntax
try {
// Code that might potentially throw an error
// ... risky operations ...
console.log("Attempting risky operation...");
let result = riskyFunction(); // Assume this might fail
console.log("Operation succeeded.");
} catch (error) {
// Code to execute if an error occurs within the 'try' block
console.error("An error occurred!");
console.error("Error name:", error.name); // e.g., "TypeError"
console.error("Error message:", error.message); // Specific error description
// console.error(error.stack); // Stack trace (more detail)
// You can decide how to handle the error here (log it, show user message, etc.)
} finally {
// Code that will always execute, regardless of whether an error occurred or not
// Useful for cleanup operations (e.g., closing resources, resetting state)
console.log("Finally block executed - cleanup can happen here.");
}
- try block: Contains the code that might throw an exception.
- catch (error) block: If an error occurs in the try block, execution jumps to the catch block. The error object contains information about the error (like its name and message). This block is optional (but usually needed if you use try).
- finally block: This block is optional. Its code executes *after* the try (and catch, if an error occurred) block finishes, regardless of whether an error happened. It's useful for cleanup actions that must always run.
Example
function divide(a, b) {
if (b === 0) {
// We'll learn to throw errors next
return "Error: Division by zero is not allowed.";
}
return a / b;
}
try {
let num1 = 10;
let num2 = 0; // Change to non-zero to see success path
console.log("Trying division...");
let result = divide(num1, num2);
console.log("Result:", result); // This might not run if error occurs before
} catch (err) {
// This specific example doesn't throw a catchable error yet,
// but shows where one *would* be caught.
console.error("Caught an error:", err.message);
} finally {
console.log("Division attempt finished.");
}
Using try...catch allows your program to handle errors gracefully instead of abruptly stopping.