DEV Community

Rakshambika
Rakshambika

Posted on

Error Handling in js

What is Error Handling?

Error handling is the process of managing errors that occur during program execution so that the application doesn't crash unexpectedly.

JavaScript provides:

  • try
  • catch
  • finally
  • Throw

Why Error Handling?

Without error handling:

console.log("Start");
let result = 10 / x; // x is not defined
console.log("End");
Enter fullscreen mode Exit fullscreen mode

Output:

Start
ReferenceError: x is not defined
Enter fullscreen mode Exit fullscreen mode

The program stops when the error occurs.

1. try...catch

  • The try block contains code that may cause an error.
  • The catch block handles the error.

Syntax

try {
    // risky code
} catch(error) {
    // handle error
}
Enter fullscreen mode Exit fullscreen mode

Example

try {
    console.log(x);
} catch(error) {
    console.log("Error occurred");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Error occurred
Enter fullscreen mode Exit fullscreen mode

2. Accessing Error Information:

The error object contains details about the error.

try {
    console.log(x);
} catch(error) {
    console.log(error);
}
Enter fullscreen mode Exit fullscreen mode

Output:

ReferenceError: x is not defined
Enter fullscreen mode Exit fullscreen mode

Useful Properties

try {
    console.log(x);
} catch(error) {
    console.log(error.name);
    console.log(error.message);
}
Enter fullscreen mode Exit fullscreen mode

Output:

ReferenceError
x is not defined
Enter fullscreen mode Exit fullscreen mode

3. finally

  • The finally block always executes whether an error occurs or not.
try {
    console.log("Try block");
} catch(error) {
    console.log("Catch block");
} finally {
    console.log("Finally block");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Try block
Finally block
Enter fullscreen mode Exit fullscreen mode

Example with Error

try {
    console.log(x);
} catch(error) {
    console.log("Error handled");
} finally {
    console.log("Always executes");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Error handled
Always executes
Enter fullscreen mode Exit fullscreen mode

4. throw

  • The throw keyword is used to create custom errors.

Example

let age = 15;

try {
    if (age < 18) {
        throw new Error("You must be 18 or older");
    }

    console.log("Eligible");
} catch(error) {
    console.log(error.message);
}
Enter fullscreen mode Exit fullscreen mode

Output:

You must be 18 or older
Enter fullscreen mode Exit fullscreen mode

Top comments (0)