Error Handling using Try/Catch in JS - ByteScout
  • Home
  • /
  • Blog
  • /
  • Error Handling using Try/Catch in JS

Error Handling using Try/Catch in JS

Error Handling using Try/Catch in JS

Error Handling in Javascript

Error handling is the technique by which users avoid errors or exceptions to disrupt the program’s flow during the run-time. Mainly, these errors result at the end of the program’s execution or crash while doing critical work. Therefore, the users get the “program crashed” notification while running the program.

Javascript is a loosely coupled programming language, and most of the errors occur during run-time instead of compile time. For instance, the user may try to change the properties of some element on the DOM which does not exist or has a different id or try to reference the variable that he has not declared yet or is not in the scope of the function. Therefore, it is a good practice to do proper error handling while writing a program to save the user from unnecessary crashes, and the program can easily change the direction of execution if something goes wrong.

Error Handling Statements in Javascript

Following are the statements used in Javascript to control the program flow in case of unexpected errors:

1.    try

The try statement contains the code to run under normal circumstances. Usually, programmers enclose that code in this block where the exceptions can occur. For instance, in a division problem, if both values, numerator and denominator, are unknown and the code calculates them during run-time, the denominator could be zero, and any number divided by zero gives an undefined value. Therefore, an exception may occur in this situation.

2.    catch

This statement contains the code to handle any error while executing the above code block. This block typically catches the errors, interprets them, resolves them, or changes the program flow accordingly. For instance, the division by zero raises an “arithmetic exception: division by zero” error, and the catch block can catch, modify the denominator, perform division again, and inform the user of the exception without stopping the program’s execution.

3.    throw

This statement defines the custom error, and users can catch that particular error in the catch block, controlling the variable values and the program’s flow. For instance, a user can throw an exception of “too small number” when entering a number less than seven for a variable.

4.    finally

This statement directs the program to run the predefined code regardless of its results. The users can use it after the try and catch block to execute the code that needs to be executed regardless of what happened in the try and catch block. For instance, the division by zero or any number has nothing to do with the color modification of the button on the user’s screen. So, the user can perform division to try and catch the block and modify the button’s color in the finally block.

Note: If the button already exists, the button’s id may also go wrong, so in real-life scenarios, the users should put such statements that refer to the DOM elements in the try and catch block.

Errors in Javascript

Following are the errors or exceptions that may occur in the run-time:

1.    Syntax error

The syntax error occurs when the user runs the program with the incorrect source code, i.e., the code containing punctuation or spelling mistakes.

2.    Reference error

The reference error occurs when the user tries to refer to or use the variable that he has not declared yet or as declared later in the code.

3.    Range error

The range error occurs when the user uses the number that is out of range for that particular function or variable.

4.    Type error

This type of error occurs when the user uses an unexpected value. For instance, if he tries to convert digits to lower or upper case, he will encounter this error.

5.    URI error

The URI error occurs when the user enters the values that are not allowed in the URI function, for instance, alphanumerics.

Examples using try and catch blocks in Javascript

Following are the examples of errors and error handling in javascript using try and catch blocks:

Syntax error without try and catch block

In the below sample code, the user tries to display an alert box on the user’s screen with the message but writes the incorrect command with the wrong spellings. An error occurs when the program tries to run this command, and the program’s execution stops without executing the code below the incorrect command.

addlert('Hello Word!')

Syntax error with try and catch block

Below is the same code but with the try and catch block. In this sample code, the try block contains the incorrect command with the wrong spellings. The catch block below the try block is there to catch the error in the try block. Therefore, when the program tries to execute this statement with the wrong spellings, it throws an error that the catch block catches and prints on the user’s console. As the catch block has already caught the error, the rest of the program can run without crashing.

try {
   addlert('Hello World')
catch(err) {



Example with a try, catch, and throw block

The programmers use the throw statement to define their custom errors that are not precisely  the programming errors. The program can run smoothly without these user-defined errors. However, in some scenarios, the users do not want the particular outcome of some calculation or do not want the program’s user to enter some particular values. In the sample code below, the program takes a value from some element on the user’s DOM and checks the value. If the value is zero, it throws a “field empty” exception. If the value exceeds fifty, it throws a “value too large” exception, and if the value is below zero, it throws a “negative value” exception. Now, the catch block is below the try block to catch all these user-defined exceptions, and whenever an exception occurs, it displays the exception to the program’s user.

ar temp = document.getElementById('element1').value;

try {
   If (temp == 0) throw 'field empty';
   else if ( temp < 0 ) throw 'negative value';
   else if ( temp > 50 ) throw 'value too large';

catch (err) {

Note: The throw exception could be a string, boolean, integer, or object.

Using the finally statement with the try and catch

The programmers widely use this statement along with the try and catch block to write the code commands that the program has to run irrespective of the outcome of the try and catch block. Below is the sample code to explain the working of the throw statement. As explained earlier, the sample code uses the above division example, performs the division in the try block, and catches any exception in the catch block. Then, below the try and catch block is the “finally” block, which contains the code that the program must execute irrespective of the action that occurred in the try and catch block. So, the program runs, performs division, and enters this block in which it prints a statement on the user’s console before terminating the program.

function division ( x, y) {
   try {
      z = x/y;
  catch (err) {

  finally {
     console.log('division performed')

About the Author

ByteScout Team ByteScout Team of Writers ByteScout has a team of professional writers proficient in different technical topics. We select the best writers to cover interesting and trending topics for our readers. We love developers and we hope our articles help you learn about programming and programmers.