Skip to content

Error Handling In Javascript

Error handling in JavaScript is an essential part of building robust applications. It allows you to gracefully handle unexpected situations, prevent crashes, and provide useful feedback to users or developers. JavaScript provides several mechanisms for error handling, primarily through try, catch, finally, and throw.

  1. try block: Code that might throw an error is placed inside the try block.
  2. catch block: If an error occurs in the try block, the catch block is executed. You can access the error object in the catch block.
  3. finally block: Code in the finally block runs regardless of whether an error was thrown or not.

Types of Errors
JavaScript has several built-in error types that you can throw or catch:

  • Error: The generic error type.
  • TypeError: Thrown when a value is not of the expected type (e.g., calling a non-function).
  • ReferenceError: Thrown when accessing a variable or property that doesn’t exist.
  • SyntaxError: Thrown when JavaScript code cannot be parsed due to incorrect syntax.
  • RangeError: Thrown when a value is outside the allowable range.
  • EvalError: Thrown when the eval() function is used inappropriately.
try {
// Code that may throw an error
let result = someFunction(); // This might throw an error
} catch (error) {
// Code that runs if an error occurs in the try block
console.error('An error occurred:', error.message);
} finally {
// Code that always runs, no matter what
console.log('Cleanup or final operations');
}

Sometimes, you might want to explicitly throw an error in your code to indicate that something has gone wrong.

function validateAge(age) {
if (age < 18) {
throw new Error("Age must be at least 18");
}
return "Valid age";
}
try {
console.log(validateAge(16));
} catch (error) {
console.error(error.message); // "Age must be at least 18"
}