Error Handling in Javascript

Ak Azad
2 min readNov 5, 2020

--

No matter how good you are, how experienced you are, you will be making mistakes now and then. But it’s alright, as long as you know how to handle those errors. And if you are writing your scripts in JavaScript, then you are in luck. Because in this article, we will be learning how to handle errors in JavaScript.

1. Error Objects

Before dealing with errors, we need to understand what errors are. In JS, everything is an object, well almost, and errors are no different. Error objects are thrown whenever there is a runtime error. They mostly consist of two standard properties, name and message, along with some additional non-standard properties for debugging purposes.

try{
console.log(error);
} catch (err) {
console.log(err.name);
console.log(err.message);
console.log(err.stack);
}

2. try-catch

In JS, with any kind of runtime error, the execution just stops given us minimal opportunity to deal with the situation. But with try…catch, we can handle the situation to a certain extent. The try block holds the regular statements to execute. The catch block only comes into play when there is an exception in the try block.

try{ console.log(‘start’);
console.log(finish); // ReferenceError
} catch (err)
{ console.log(‘We have an error’);
}

3. try-catch-finally

The finally block gives us the ability to execute certain statements, regardless of whether an exception is thrown from the try block. finally block makes our code more predictable.

try{ console.log(‘start’);
console.log(finish);
} catch (err)
{ console.log(‘We have an error’);
} finally { console.log(“I’m always here!”);
}

4. throw Statement

Until now, it was up to JS to decide if something is right or wrong. But with throw, we can set our own error conditions and throw exceptions at will. The throw stops the execution of the current function and pass the control to the catch block if available.

try{ const a = 1;
const b = -4;
const sum = a+b;
if(sum < 0){ throw ‘Error: Negative Number!’;
} console.log(sum);
} catch (err)
{ console.log(err);
}

--

--

Ak Azad
Ak Azad

Written by Ak Azad

0 Followers

I am AK Azad, I am studying computer science and engineering

No responses yet