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

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 … 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’.

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,

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.

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,

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abdullah Alamin

Full Stack Web Developer | Javascript, React and Node Expert.