Javascript Try Catch Throw Finally Error – What it is & How to Fix it?

Javascript Try Catch Throw Finally Error – What it is & How to Fix it?

Irrespective of how good you are in coding, you will always come across errors. Handling errors, exceptions, and bugs is an everyday job for all programmers irrespective of the software language used. Usually when an error or exception occurs the application terminates suddenly. To avoid the sudden crashing of applications we can make use of try-catch statements. Now let us understand what is try-catch in Javascript and how can we implement it in our code.

Try-catch syntax

The try-catch in JavaScript is similar to if-else statements but try/catch gives you the upper hand in any situation which we will discuss later. Here is the syntax of a try-catch in JavaScript:

......... // checks for errors
} catch(e){
....... // catches the error if any

The try block helps you to test a piece of code for errors. While the catch block helps you to deal with the error in the try statement. First, you need to put the code you want to check in the try block. If any error is there JavaScript gives control to the catch block which executes the code you have mentioned there.

For instance, in the below given example in the try block, we called a function that is not defined. This will throw an error that will get caught by the catch block and will send us an alert message of the error.

helloWorld() // this function is not defined
} catch(e){
alert(e) // gives us an alert message of the error

What is an error object?

In JavaScript all errors are objects and they have two properties: the name of the errors and the textual message associated with them. For instance, for an error object e, we can access this error’s name and message by simply writing, and e.message.

In JavaScript, errors are divided into six main categories:

  1. ReferenceError – Error when you try to access or use an undefined object, variable, or function.
  2. RangeError – When the number is given is out of range.
  3. EvalError – An error that occurs due to the eval function
  4. SyntaxError – Incorrect or misuse of syntax while compiling the code gives rise to this error.
  5. URI Error- Occurs when you use incorrect characters in a URI (Uniform Resource Identifier) function.
  6. TypeError – Usage of wrong datatypes in the program.

Throwing user-defined errors

As mentioned earlier, try-catch in Javascript provides many benefits, unlike the if-else statements. Try catch statements offers us the throw statement which has the ability to showcase your own custom-made error. There are times when you have a specific message for a certain pre-defined error or you want JavaScript to check and throw your own exception or error.

You can do these two tasks by making use of the throw statement in JavaScript. This error can be an object, string, or boolean. If there is any sort of error in the try statement then the catch statement will detect it and display the error you have thrown. Here is how to you the throw statement with try-catch in JavaScript:

let num = prompt('Enter a positive number')
try{ if(isNaN(num)) throw "Please enter an number" 
else if (num<0) throw "Number not positive" 
else alert("Thank you")

Finally Statement

There is one more benefit of using try-catch in JavaScript, you can use the finally statement. The finally block behaves like a base point or a neutral stand for your try-catch. With the help of this, you can execute a piece of code irrespective of what happens in the try-catch blocks. If there is an error or there is no error, the code you write in the finally block will always get executed. Here is how you can use the finally block with try-catch in JavaScript:

let data=prompt("name")
if(data==="") throw new Error("data is empty") 
else alert(`Hi ${data} how do you do today`) 
} catch(e){ 
} finally { 
alert("welcome to the try catch article")
let person = prompt("Please enter your name")
if(data==="") throw new Error("Please enter name")
else alert("Welcome "+person)
} catch(e){
} finally{
alert("Welcome to my account")

Global catch

There are times where there is an unexpected error outside the try-catch blocks. This error can lead to the sudden crashing of the applications. In the above-mentioned case, you can make use of the global catch in JavaScript. The window.onerror and element.onerror are EventTarget.addEventListener handles which inform us about error’s details. They have five parameters, message, source, lineno, colno, and an error object.

Limitations of try-catch in JavaScript

There are two types of main errors in JavaScript, Runtime exceptions and parse-time errors. The above-explained errors like EvalError, SyntaxError, and so on are subclasses of these two main errors.

Runtime errors or exceptions are those that are thrown in a valid code and they can be caught through try-catch statements. On the other hand, parse-time errors are those errors which the JavaScript engine can not interpret hence using a try-catch block in this situation will not work and your application will suddenly crash. Here is an example of a parse-time error:

} catch(e){


Remember that your code will not become errorless by using try-catch in JavaScript. These statements are used to find and understand the errors and not to rectify incorrect logic or code. Hence ensure your logic is correct according to the applications’ requirements. Receiving errors and exceptions is not a bad thing. All you need is to improve your programming skillset by practicing and learning different concepts.

Sharing is caring

Did you like what Agam singh, Aman Ahmed Siddiqui, Aman Chopra, Aman, Amol Shelke, Anas Khan, Anirudh Panda, Ankur Balwada, Anshul Soni, Arif Shaikh, wrote? Thank them for their work by sharing it on social media.


No comments so far