JS Error Handling — try…catch

Abdullah Mamun
2 min readMay 6, 2021

--

Every developer can mistakes, no matter how great they are. sometimes our code have a error. error occur because our mistakes, user given wrong input, an unexpected server response and also have a lot of reason for occur error.

How to solve this problem?

There are many solution here, one of try…catch syntax construct to catch error and handle it more reasonable.

try…catch syntax

There are two main block in try-catch.

try {

// code

} catch {

// if any error, handle it

}

How its works?

When we run the program, first try {} block executed. if there are no error happed code successfully run and also ignore the catch{} block. if any error occur in code immediately stop to try block execution. catch block got an err objects with details in the argument.

try…catch flowchart

flowchart of try-catch

When it works?

It works only for runtime errors, not for any syntactically error. when we write a valid and runnable JavaScript code. then its works only. it won’t work we get a mistakes in syntax.

try {

{ // unclosed curly braces, try … catch won’t work

} catch (err){

}

try…catch works synchronously

try…catch works synchronously, that’s why it won’t work in schedule code like setTimeout because of function will execute later. when JavaScript engine left try…catch constructor.

If I want to catch error in schedule code, try…catch must be inside in the function.

example

setTimeout( () => {

try {

var msg = 'I am calling from setTimeout inside'

console.log(msg)

}

catch { alert('oopps! an error occured!'); }

}, 1000);

Error Object

When an error occurs, JavaScript generates an object containing the details. The object is then passed as an argument to catch {}block.

Error objects have two properties, one is error name other is error message .

example

try {

// code

} catch (error) {

console.log(error)

console.log(error.name)

console.log(error.message)

}

Throwing our own errors

we can also throw our own errors. when we need to create our errors.

example

try {

if(!name) {

throw 'name is not defined'

} else {

console.log(name)

}

} catch (err) {

console.log(err)

}

summary

try...catch handle only runtime error. It’s try to execute code and catch error, if it’s occur.

let’s finish with an example:

try {

console.log('hello, i am from try block')

} catch (err) {

console.log('oopps! an occurred error', err)

}

--

--