error

Error Handling in JavaScript

Error Handling in JavaScript

Error handling helps prevent your code from crashing and allows you to respond to issues in a graceful way.

Try...Catch...Finally

Use try...catch to handle exceptions and finally to execute code regardless of success:

      
        try {
          let x = 10;
          let y = 0;
          let result = x / y;
          if (!isFinite(result)) {
            throw new Error("Cannot divide by zero");
          }
        } catch (error) {
          console.log(error.message); // Outputs: Cannot divide by zero
        } finally {
          console.log("This will run regardless of success or error.");
        }
      
    

Activity

Try It Yourself!

Write a function that catches an error when dividing by zero and displays an alert.

Quiz

Quick Quiz

  1. What is the purpose of the try...catch statement?
  2. What does finally do in error handling?
  3. What happens if an error is not caught?

Answers: To handle exceptions; executes code regardless of success; can crash the script if not handled.