try...catch in javascript

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

}        
try...catch block working

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.



要查看或添加评论,请登录

Nakeeb Raut的更多文章

  • useContext hook in ReactJs

    useContext hook in ReactJs

    ReactJs is an open source javascript library. It is used for the faster web development.

  • Custom error handling in Javascript

    Custom error handling in Javascript

    Yesterday we learnt about try..

  • async/await in Javascript

    async/await in Javascript

    Previous we learned about promises in javascript. If you haven't checked the blog, i strongly suggest to learn about…

  • Promise in javascript

    Promise in javascript

    Promise is used to handle asynchronous code in a more organized and readable way. Lets understand the concept first.

  • Callbacks in javascript

    Callbacks in javascript

    As name suggests its tells us to call back once the task is completed. A callback is a function passed as an argument…

社区洞察

其他会员也浏览了