Error Object in JavaScript
Error object is thrown when any error occurs in JavaScript.
Error object has 2 properties.
- name
- message
There can be below types of errors in JavaScript.
- ReferenceError
- SyntaxError
- TypeError
- RangeError
- EvalError
- URIError
Example on Error Object is given below.
In below example, since we have not defined x earlier in the code, error will be thrown. In catch block, we can handle that error.
try {
console.log(“Checking exception” + x);
}
catch(error) {
console.log(“Error message -> ” + error.message);
}
finally{
console.log(“Finally block is always executed no matter error is thrown or not in try block!!”);
}
Throwing custom error
Below example illustrates how to throw custom error in JavaScript.
try{
var balance=0;
if (balance==0)
{
throw new Error(“balance is 0”)
}
}catch(err){
console.log(“Error thrown -> ” + err.message)
}
Recent Comments