Error v/s Exception

dipesh_the_dev

Dipesh Tamang

Posted on June 2, 2024

Error v/s Exception

Have you ever been confused between an error and an exception? We often tend to use these words interchangeably. Well, they are not the same, since they have nuanced differences. Let us understand these differences with examples.

Error

An error usually refers to a condition that hinders a program's normal execution. It can be due to issues like:

1. Syntax Errors

Errors which occurs when we have mistakes in our code that prevents the compiler from parsing our program correctly.

// Syntax error example:
function greet() {
  console.log("Hello world!"; // SyntaxError: missing ) after argument list
}
Enter fullscreen mode Exit fullscreen mode

2. Runtime Errors

Errors that occur during the execution of the program.

  • Reference Errors: When trying to access a variable that doesn’t exist.
  • Type Errors: When an operation is performed on an incompatible type.
// Reference error example:
console.log(person); // ReferenceError: person is not defined

// Type error example:
let age = 28;
age.toUpperCase(); // TypeError: age.toUpperCase is not a function
Enter fullscreen mode Exit fullscreen mode

Exception

An exception is a specific type of error that can be anticipated, caught and handled. It allows us to handle errors gracefully and does not break the program.

Exception handling involves:

1. Throwing an Exception:

When an error occurs, the program "throws" an exception. We can throw an exception using throw keyword.

function divide(num1, num2) {
  if (num2 === 0) {
    throw new Error("Division by zero");
  }
  return num1 / num2;
}
Enter fullscreen mode Exit fullscreen mode

2. Catching an Exception:

We can handle expections using try...catch...finally block.

try {
  divide(1, 0);
} catch (error) {
  console.log(error.message); // Output: Division by zero
} finally() {
  console.log("Done");
}
Enter fullscreen mode Exit fullscreen mode

Note: finally block is optional and it is executed regardless of whether there was an exception or not.

Conclusion

In simple terms, all exceptions are errors, but not all errors are exceptions. Errors are problems that can happen in a program, while exceptions are a special type of error that you can "throw" and "catch" to handle them smoothly. Knowing the difference helps you write better and more reliable code.

💖 💪 🙅 🚩
dipesh_the_dev
Dipesh Tamang

Posted on June 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Error v/s Exception
javascript Error v/s Exception

June 2, 2024