Error handling, “try..catch”

Arifkhan
2 min readNov 4, 2020

“try…catch” syntax

try {

// code...

} catch (err) {

// error handling

}

works synchronously

That’s because the function itself is executed later, when the engine has already left the try..catch construc

try {
setTimeout(function() {
noSuchVariable; // script will die here
}, 1000);
} catch (e) {
alert( "won't work" );
}

Error object

When an error occurs, JavaScript generates an object containing the details about it. The object is then passed as an argument

try {
// ...
} catch(err) { //
// ...
}

catch binding

If we don’t need error details, catch may omit

try {
// ...
} catch { //
}

Using catch

As we already know, JavaScript supports the JSON.parse(str) method to read JSON-encoded values.

let json = '{"name":"John", "age": 30}'; // data from the server

let user = JSON.parse(json);


alert( user.name ); // John
alert( user.age ); // 30

our own errors

What if json is syntactically correct, but doesn’t have a required name property?

let json = '{ "age": 30 }'; // incomplete data

try {

let user = JSON.parse(json); // <-- no errors
alert( user.name ); // no name!

} catch (e) {
alert( "doesn't execute" );
}

Rethrowing

Of course, everything’s possible! Programmers do make mistakes. Even in open-source utilities used by millions for decades — suddenly a bug may be discovered that leads to terrible hacks.

let json = '{ "age": 30 }'; // incomplete data

try {
user = JSON.parse(json); // <-- forgot to put "let" before user

// ...
} catch(err) {
alert("JSON Error: " + err); // JSON Error: ReferenceError: user is not defined
// (no JSON Error actually)
}

try catch finally

The try..catch construct may have one more code clause: finally

try {
... try to execute the code ...
} catch(e) {
... handle errors ...
} finally {
... execute always ...
}

try..finally

The try..finally construct, without catch clause, is also useful. We apply it when we don’t want to handle errors here (let them fall through), but want to be sure that processes that we started are finalized.

function func() {
// start doing something that needs completion (like measurements)
try {
// ...
} finally {
// complete that thing even if all dies
}
}

Global catch

Let’s imagine we’ve got a fatal error outside of try..catch, and the script died. Like a programming error or some other terrible thing.

window.onerror = function(message, url, line, col, error) {
// ...
};

--

--