try…catch in JavaScript

SM. ASFAKUR RAHMAN SAIKAT
1 min readMay 6, 2021

Try catch or Error handling is called defense for a programming language. JavaScript has also support powerful features of error handling.

try {

//here the statement will be placed if there has a doubt about it

}

catch (err) {

//if errors occurs in the above try block then it will be caught

}

lets see an example

try {

number; //this variable is not defined at all

} catch (err) {

console.log(err.name); //ReferenceError

console.log(err.message); //number is not defined

}

In the above example number variable is not defined so that error is caught in catch block and the error name and error message is printed

Lets see another example

try {

const number = 10;

number = 40;

} catch (err) {

console.log(err.name); //TypeError

console.log(err.message); //Assignment to constant variable.

}

In second example in const type variable is reassigned that is an error. So type error is caught in catch block

--

--