J

JavaScript Handbook

Clean • Professional

JavaScript Error Handling

2 minute

JavaScript Error Handling

In JavaScript, errors are unexpected conditions that occur during the execution of code. They interrupt normal program flow and can arise due to syntax mistakes, logical flaws, or runtime issues like accessing undefined variables, invalid operations, or failed network requests. Understanding how JavaScript handles errors is essential for building robust, fault-tolerant applications.

JavaScript categorizes errors into a few main types:

1. SyntaxError – Occurs when the code is not valid JavaScript syntax.

Example:

eval('alert("Hello)');
// SyntaxError: Unexpected end of input

2. ReferenceError – Happens when code references a variable that is not defined.

console.log(x);
// ReferenceError: x is not defined

3. TypeError – Raised when a value is not of the expected type.

null.f();
// TypeError: Cannot read properties of null

4. RangeError – Generated when a numeric value is out of allowable range.

let arr = new Array(-1);
// RangeError: Invalid array length

5. EvalError – Rare, related to misuse of the eval() function.

6. URIError – Occurs when encodeURI() or decodeURI() receives invalid input.

Handling errors properly allows the program to continue running smoothly even after encountering unexpected situations.

try…catch…finally

JavaScript provides the try…catch…finally block to handle runtime errors gracefully.

  • try: Contains code that might throw an error.
  • catch: Executes if an error occurs in the try block. Receives the error object as an argument.
  • finally: Executes after try and catch, regardless of whether an error occurred, usually for cleanup tasks.

Example:

try {
  let result = riskyOperation();
  console.log(result);
} catch (error) {
  console.error("An error occurred:", error.message);
} finally {
  console.log("Cleanup actions, always executed.");
}

throw Statement

The throw statement allows developers to generate custom errors deliberately. This is helpful when certain conditions must trigger an exception.

Example:

function divide(a, b) {
  if (b === 0) {
    throw new Error("Division by zero is not allowed");
  }
  return a / b;
}

try {
  console.log(divide(10, 0));
} catch (err) {
  console.error(err.message); // Division by zero is not allowed
}

Custom Errors

Custom errors are user-defined error types that extend the built-in Error class. They provide more semantic meaning and can help in debugging and maintaining code.

Example:

class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}

function validateAge(age) {
  if (age < 0 || age > 120) {
    throw new ValidationError("Age must be between 0 and 120");
  }
  return true;
}

try {
  validateAge(150);
} catch (err) {
  console.error(err.name + ": " + err.message); // ValidationError: Age must be between 0 and 120
}

 

Article 0 of 0