Error Handling in JavaScript

Error handling in JavaScript ensures that your application can handle unexpected situations gracefully instead of crashing or behaving unpredictably. Errors can occur due to invalid input, network failures, logic mistakes, or unexpected runtime conditions. JavaScript provides structured tools to detect, throw, and manage errors effectively.


Why Error Handling Matters

  • Prevents application crashes
  • Improves user experience with meaningful messages
  • Makes debugging easier
  • Helps maintain stable, production-ready applications

1. try...catch

The try...catch statement is the core mechanism for handling runtime errors in JavaScript.

try {
  // Code that may throw an error
} catch (error) {
  // Code that runs if an error occurs
}
  • try block → Contains code that might fail
  • catch block → Executes if an error occurs in try
  • error → An object containing details like name and message

Example: Basic try...catch

try {
  let result = 10 / 0;
  console.log(result); // Infinity (no error)

  let person = undefined;
  console.log(person.name); // Error
} catch (error) {
  console.log("An error occurred:", error.message);
}

✅ Instead of crashing, the error is caught and handled safely.


1.1 finally Block

The finally block executes regardless of whether an error occurs or not.
It is commonly used for cleanup tasks.

Example

try {
  let result = 10 / 2;
  console.log(result);
} catch (error) {
  console.log("Error:", error.message);
} finally {
  console.log("This always runs.");
}

✅ Use finally for:

  • Closing files
  • Clearing timers
  • Releasing resources

2. Throwing Errors

JavaScript allows you to manually throw errors using the throw keyword. This is useful when validating conditions or enforcing rules.

throw new Error("Error message");

Example: Throwing an Error

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

try {
  console.log(divide(10, 2)); // 5
  console.log(divide(10, 0)); // Error
} catch (error) {
  console.log("Error:", error.message);
}

✅ Throwing errors lets you control when and why a failure occurs.


3. Custom Errors

JavaScript allows you to create custom error classes by extending the built-in Error class. This helps differentiate between different error types and improves readability.


3.1 Creating a Custom Error Class

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

function validateInput(input) {
  if (!input || input.length < 5) {
    throw new ValidationError("Input must be at least 5 characters long.");
  }
  return input;
}

try {
  validateInput("abc");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log("Validation Error:", error.message);
  } else {
    console.log("General Error:", error.message);
  }
}

✅ Custom errors allow precise error handling.


3.2 Multiple Custom Errors

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

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

try {
  throw new AuthenticationError("User is not authenticated.");
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.log("Authentication Error:", error.message);
  } else if (error instanceof AuthorizationError) {
    console.log("Authorization Error:", error.message);
  } else {
    console.log("General Error:", error.message);
  }
}

✅ This pattern is very common in real-world applications (auth, APIs, validation).


4. Best Practices for Error Handling

✅ Handle Errors Gracefully

Always provide meaningful feedback and keep the app running.

✅ Use Specific Errors

Custom error classes improve clarity and debugging.

❌ Avoid Silent Errors

Never catch errors without logging or handling them.

✅ Use finally for Cleanup

Ensure resources are released even if an error occurs.

✅ Throw Meaningful Messages

Error messages should help developers understand the cause.


Common Error Types in JavaScript

Error TypeDescription
ErrorGeneric error
TypeErrorInvalid type operation
ReferenceErrorUndefined variable
RangeErrorValue out of range
SyntaxErrorInvalid syntax

Summary

JavaScript error handling ensures robust and stable applications by:

  • Catching runtime errors using try...catch
  • Manually throwing errors with throw
  • Creating custom error types for clarity
  • Using finally for cleanup tasks

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *