Try… Catch | JavaScript| A Game Between Code and Error…

Nayeem Uddin
2 min readNov 3, 2020

A coder weather he is a experienced or a newbie faces errors in their life. Its a normal thing to happen in codes life.

As a new JavaScript Developer I face this too. While I’m learning JavaScript I came to know a very unique thing which is try catch. here I’m to explain what I've learned so far.

  1. try and catch these re two different block

example

try{

// here is your code

}

catch{

//handles your errors

}

2. In the try section you will write your actual code. But the interesting thing is if you code has any errors it will be caught in the catch section and show you a message that you wrote in the catch section.

3. We all know that java script is asynchronous right? Which means it can execute code which if wrote write above.

But while we come to try catch, this is synchronous . Which means these will execute top to bottom, like he 1st one then the 2nd and so on.

example:

try{

const numOne = 68;

const numTwo = 70;

} catch(err){

console.log(‘hey, you got an error!!’)

}

Here catch section will be avoided because there is no problem in the try section.

4. Lets make a mistake in try section.

try{

const numOne = 68;

70;

} catch(err){

console.log(‘hey, you got an error!!’)

}

Now Here, If you use (console.log(numOne)) after the variable declared anf try to run it we’ll see 68 and then variable not declared. Which means we’ll enter in the catch section…// hey, you got an error!!

5. So the thing is synchronous it will try to execute the code in the try section step by step, If there is no problem catch will be ignored and finds a problem catch will be executed…

6. There is one thing that should be kept in mind that, you cannot make syntax errors. Which means you have to write it in a proper way..

Try{

{{[]

} catch(err){

console.log(‘You made a mistake’)

}

Code above will not be executed because we’ve wrote a code which is syntactically wrong.

7. Sometime if you dont need to see the error message, you can blind the catch…

try{

const num = 27;

}catch{}

see the code above, catch is empty. If there an error you’ll nor see any message but It will run…

So, thats the thing… you’ll heard this thing in you’re JavaScript career. The Game Is Just On….

--

--