JavaScript Error Handling and Debugging

What is Error Handling?

In JavaScript, error handling is done using `try...catch` blocks. Errors can be handled gracefully without stopping the execution of the program. Debugging is the process of identifying and fixing errors in your code.

1. Try...Catch

The `try...catch` statement allows you to test a block of code for errors and handle them without stopping the entire program.


try {
    let result = riskyFunction();
} catch (error) {
    console.error("An error occurred:", error);
}
        

2. Throwing Errors

You can throw custom errors using the `throw` keyword. This helps in defining your own error messages when something goes wrong in your program.


function checkAge(age) {
    if (age < 18) {
        throw new Error("Age must be 18 or older!");
    }
    return "Age is valid.";
}
        

3. Debugging Tools

Debugging JavaScript code can be done using tools like `console.log()`, `debugger`, or even browser developer tools (DevTools).

For example, you can use `console.log()` to print the value of variables to the console to understand the program's behavior.


let x = 10;
console.log("The value of x is:", x);
        

Interactive Example

Try throwing an error and catching it:

Quiz: Test Your Knowledge

1. What does the `try` block in a `try...catch` statement do?




2. What does the `throw` keyword do?




3. What is the purpose of `console.log()`?