"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

Error Handling

 

When something goes wrong in JavaScript—like invalid input, missing variables, or network issues—it can cause errors that stop your code from running. Error handling lets you detect and manage these problems without crashing your app.


1. The try...catch Statement

The try...catch block is used to handle errors gracefully.

try {

  let result = 10 / 0; // This won't throw an error, but...

  console.log(result); // Infinity

  undefinedFunction(); // This will throw an error

} catch (error) {

  console.log("An error occurred:", error.message);

}


2. finally Block

The finally block runs no matter what—whether an error occurred or not.

try {

  let data = JSON.parse('{"name": "John"}');

  console.log("Parsed:", data);

} catch (error) {

  console.log("Error parsing JSON:", error.message);

} finally {

  console.log("Execution completed!");

}


3. Throwing Your Own Errors

You can create custom errors using throw.

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 (error) {

  console.log(error.message); // Division by zero is not allowed!

}


4. The Error Object

The Error object provides details about the error:

try {

  nonExistentFunction();

} catch (error) {

  console.log(error.name); // ReferenceError

  console.log(error.message); // nonExistentFunction is not defined

  console.log(error.stack); // Stack trace

}


5. Common Error Types

  • ReferenceError – Variable not defined
  • TypeError – Invalid data type usage
  • SyntaxError – Invalid JavaScript syntax
  • RangeError – Number out of range

 

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)