Don’t catch Your Girlfriends error, catch your programs Error😂— JavaScript
What is Error?
Every programmer in the world is familiar with the word is “Error”. From beginner to expert, a programmer always has been the victim of this trouble. It is a problem that occurs in the program. Today, I will talk about handling of error that is “try…catch”. Here, try means test a block of codes for checking errors. And catch statement helps to handle the error.
The “try…catch” syntax
There are two blocks in “try…catch”, try and catch.
try {
// code testing process
} catch (err) {
// error handling process
}
From the flowchart:
- Firstly, try statement is executed.
- If no errors occurred, it simply ignores catch statement but if errors occurred, it ignores try statement and execute catch statement.
An example about this:
try {alert(‘try runs because the code has no errors’);} catch (err) {alert(‘Catch error’); // (3)}
Do You know try…catch only works for runtime errors?
A program during execution is called runtime errors. The main purpose of try…catch to work, the code must be runnable.
try {
{{{{{
} catch (err) {
alert(“Error has occured”);
}
try…catch works synchronously
If a programmer used setTimeOut method, then try catch won’t catch it.
try {
setTimeout(function() {
myVariable
}, 1100);
} catch (err) {
alert( “didn't work” );
}
But, if you want to catch an exception inside a function try…catch must be used.
setTimeout(function() {
try {
myVariable;
} catch {
alert( “Error” );
}
}, 1000);
Error Object
When an error occurs, JavaScript generates an object that are passed as an argument to catch.
try {
// code
} catch (err) { //error object
// code
}
“catch” binding
If we don’t need any details information about error, catch may ignore it.
try {
// code
} catch { // without err
// code
}
Using “try…catch”
Let’s go to a real life example, JSON. We mainly used to get the decoded data by using JSON parsing. A simple example of JSON is:
json = ‘{“name”:”Mahmudur”, “age”: 23, “occupation”: “Web Developer”}’;
If the json is not correct, it generates an error.
let json = “{ wrong json }”;
try {
let user = JSON.parse(json);
alert( user.age ); // doesn’t work
} catch (err) {
alert( err.name );
alert( err.message );
}
Own errors
Sometimes, you see that json is syntactically correct but you don’t have a occupation property. See this.
let json = ‘{ “age”: 23 }’;try {
let user = JSON.parse(json); // ← no errors
alert( user.occupation );
} catch (err) {
alert( “no execution” );
}
instanceof operator
We can check the type of error by using instanceof operator.
try {
varA = { /*…*/ };
} catch (err) {
if (err instanceof ReferenceError) {
alert(‘Error has occured’);
}
}
Reference error mainly used for undefined variable.
try…catch…finally
finally statement used to execute the code after try and catch. The code is:
try {
// code
} catch (err) {
// code
} finally {
// code
}
Today, that’s all about this. Thank You. 😉