2 min read

Error Handling

Error handling is a critical part of writing robust JavaScript code. When an error occurs, it's important to handle it gracefully so that your application doesn't crash.

try...catch

The try...catch statement allows you to "try" a block of code, and if an error occurs, you can "catch" it and handle it.

try {
  // Code that might throw an error
  const result = someFunctionThatMightFail();
  console.log(result);
} catch (error) {
  // Code to handle the error
  console.error('An error occurred:', error.message);
}

The error object in the catch block contains information about the error, such as its name and message.

finally

The finally block will always execute, regardless of whether an error was thrown or not. This is useful for cleanup tasks, like closing a file or a database connection.

try {
  // ...
} catch (error) {
  // ...
} finally {
  console.log('This will always run.');
}

throw

You can create your own custom errors using the throw statement.

function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero!');
  }
  return a / b;
}

try {
  const result = divide(10, 0);
  console.log(result);
} catch (error) {
  console.error(error.message); // "Cannot divide by zero!"
}

You can throw any value, but it's best practice to throw an Error object (or a custom error class that extends Error).

Error Types

JavaScript has several built-in error types:

  • Error: The base type for all errors.
  • SyntaxError: An error in the code's syntax.
  • ReferenceError: An error when trying to access a variable that is not defined.
  • TypeError: An error when a value is not of the expected type.
  • RangeError: An error when a value is outside a valid range.

By checking the type of the error, you can handle different errors in different ways.