Javascript For Dummies: Try & Catch
Error is a common word for programmers. And if it is Javascript, the chance gets a height. In this article we are going to learn how to handle error with try and catch block.
Syntax
try{
//... execute your code here
} catch (error){
//...do what you want
}
While executing the code in try block, if any error occurs, the execution stops and it straightforward jumps to the catch block.
‘Error’ object
You see an ‘error’ object as an argument in the catch block. What does that mean? or What properties does it contain?
This error object mainly has two properties. ‘name’ and ‘message’.
try{variable; // undefined variable} catch(err){console.log(err.name); // ReferenceErrorconsole.log(err.message); // variable is not defined}
Try … Catch … Finally
Suppose you have some code that needs to be executed irrespective of the success in the try block or failure. You can do that using a new block ‘finally’.
try{// ... your codeconsole.log('in the try block');} catch(err){console.log('in the catch block');} finally {console.log('I get executed in either state.');}
If everything is ok in the try block, the code will console ‘in the try block’ and then ‘I get executed in either state.’
Else if any error occurs in the try block the code stops running and jumps to the catch block, consoles ‘in the catch block’ and then ‘I get executed in either state’.
Throwing error
In Javascript we can throw an error with,
throw <error>
In the error section, you can give any value i.e. string, number or object.
But the convention is providing an error object. We can do it with built-in methods.
throw new Error('Your error message comes here');
This will automatically get converted into an object with two basic properties — name and message. The message is what you provide in the parentheses and the name is what error object you use. For example,
new Error(message); //
new SyntaxError(message); // err.name = SyntaxError, err.message = message.
new ReferenceError(message);// err.name = ReferenceError
Types of Errors
There are seven types of basic errors in Javascript. Those are-
— Syntax error
— Reference error
— RangeError
— TypeError
— URIError
— EvalError
— InternalError
We will talk in detail about all these errors in a later time.