try...catch in javascript
Doesn't matter how much experienced we are, we as a human, are prone to make errors in our code. They may occur due to mistakes or unexpected reasons.
Usually the execution "dies" as soon as any error occurs.
But we have try...catch for the rescue. It catches the error and ensure a smooth flow by allowing us to take necessary actions. Its structure looks like below
try{
//some code
}catch(error){
//what to do if error occurs
}
One thing to be remembered is try...catch works only for the executable code.
let us understand what that means.
It will work for
try{
cbvcxvbxvcc;
}catch(err){
console.log("In catch")
console.log(err)
}
but not for
try{
{{{{{;
}catch(err){
console.log("In catch")
console.log(err)
}
Reason is simple. Javascript compiler first reads the code. first code is syntactically correct so js executes it and goes to catch if there is error.
领英推荐
In second case, js cant understand the code and so it can't handle the error.
Also one more thing that should be taken care of is use of callback function e.g setTimeout functions
try{
setTimeout(()=>{
sdfjdklf; (*)
},1000);
}catch(err){
console.log(err);
}
In above case the error will not be catched. Rather the code will die at (*) after 1 second.
The reason is, the compiler has moved from try catch already and after 1 second, there is no catch block to catch the error.
In order to catch such errors, we can do like below
setTimeout(() => {
try{
kdsjklfsjl;
}catch(err){
console.log(err);
}
},1000);
Now the we can console error even after 1 second.
To learn more about js basics, Please visit my profile.