JavaScript try…catch Statement

Summary: in this tutorial, you will learn how to handle errors by using the JavaScript try...catch statement.

Introduction to JavaScript try...catch statement

To handle errors in JavaScript, you use the try...catch statement:

try { // code may cause error } catch(error){ // code to handle error }
Code language: JavaScript (javascript)

In this statement, you place the code that may cause errors in the try block and the code that handles the error in the catch block.

If an error occurs, JavaScript terminates the code execution and jumps to the catch block.

In the catch block, you can access an error object that contains at least the name of the error and message that explains the error in detail.

Different web browsers may add more property to the error object. For example, Firefox adds filename, lineNumber, and stack properties to the error object.

The following flowchart illustrates the flow of the try...catch statement:

javascript try catch

See the following example:

try { nonExistingFunction(); } catch(error){ console.log(error.name + ":" + error.message); }
Code language: JavaScript (javascript)

Output

ReferenceError:nonExistingFunction is not defined
Code language: JavaScript (javascript)

In this example, we called the nonExistingFunction() function in the try block.

However, the nonExistingFunction() function doesn’t exist, therefore, JavaScript throws an error.

In the catch block, we showed the name and message properties of the error object. The name of the error is ReferenceError and its message is nonExistingFunction is not defined.

The finally clause

The finally clause is an optional clause of the try...catch statement. The code that you place in the finally block always executes whether the error occurs or not.

It means that if the code in the try block executes entirely, the code in finally block executes; In case an error occurs that causes the code in the  catch block executes, the code in the finally block also executes.

The following flowchart illustrates the flow of the try...catch...finally statement:

Consider the following example:

function test(){ try { return 1; } catch(error) { return 2; } finally { return 3; } } console.log(test());
Code language: JavaScript (javascript)

What will show in the output? 1, 2 or 3. The answer is 3.

It seems that the test() function will return 1 because no error occurs in the try block and it has the return statement.

However, the presence of the finally clause makes the return statement in the try block to be ignored.

If you remove the finally clause, the test() function will return 1.

Note that once you use the finally clause, the catch clause becomes optional.

It means that you can use only try...finallyclause:

try { // code that may cause an error } finally { // code to cleanup resources }
Code language: JavaScript (javascript)

Since the code in the finally always executes, it is a perfect place to put the code that releases the resources, like this:

let connection = { open: function () { console.log('open a connection'); }, close: function () { console.log('close the connection'); } }; try { connection.open(); } catch (error) { console.log(error.message); } finally { connection.close(); }
Code language: JavaScript (javascript)

In this example, we called the close() method of the connection object in the finally clause to close the connection whether an error occurs or not.

JavaScript error types

JavaScript has different types of errors that may occur during the code execution:

  •  Error
  •  EvalError
  •  RangeError
  •  ReferenceError
  •  SyntaxError
  •  TypeError
  •  URIError

The Error type is the base type of other error types. Let’s examine in detail when JavaScript throws each type of error.

EvalError

JavaScript throws the EvalError when you use eval() as anything other than a function call, for example:

let e = new eval();
Code language: JavaScript (javascript)

Error:

TypeError: eval is not a constructor
Code language: JavaScript (javascript)

However, web browsers often throw the TypeError instead of EvalError in this situation.

RangeError

The RangeError occurs when a number is not in its range. See the following example:

try { let list = Array(Number.MAX_VALUE); } catch (error) { console.log(error.name); // "RangeError" console.log(error.message); // "Invalid array length" }
Code language: JavaScript (javascript)

Error

RangeError Invalid array length
Code language: JavaScript (javascript)

The code in the try block causes a RangeError because we used an invalid length to define a new array.

ReferenceError

The ReferenceError occurs when you reference a variable, a function, or an object that does not exist.

try { var a = a + b; } catch (error) { console.log(error.name); // "ReferenceError" console.log(error.message); // "b is not defined" }
Code language: JavaScript (javascript)

Error:

ReferenceError b is not defined
Code language: JavaScript (javascript)

In this example, the variable b does not exist therefore it causes a ReferenceError.

SyntaxError

The SyntaxError occurs in a string that you pass to the eval() function, for example.

try { eval('a x b'); } catch (error) { console.log(error.name); // "SyntaxError" console.log(error.message); // "Unexpected identifier" }
Code language: JavaScript (javascript)

Error

SyntaxError Unexpected identifier
Code language: JavaScript (javascript)

Outside the eval() function, JavaScript stops executing the code whenever it finds a SyntaxError.

TypeError

The TypeError occurs when a variable is of an unexpected type or access to a nonexistent method.

try { let x = new "String"; } catch(error) { console.log(error.name); // "TypeError" console.log(error.message); // "String" is not a constructor" }
Code language: JavaScript (javascript)

Error:

TypeError "String" is not a constructor
Code language: JavaScript (javascript)

In this example, we tried to create a new instance of a literal string which caused a TypeError error.

let db = { host: 'localhost', port: 3306, user: 'root', password: 'secret' }; try { db.connect(); } catch (error) { console.log(error.name); // "TypeError" console.log(error.message); // "db.connect is not a function" }
Code language: JavaScript (javascript)

In this example, we tried to access the connect() method of the db object, which does not exist, therefore a TypeError error occurred.

URIError

The URIError error occurs when using the encodeURI() or decodeURI() with a malformed URI, for example:

console.log(encodeURI('\uDFFF'));
Code language: JavaScript (javascript)

Throwing errors

To throw an error, you use the throw operator. For example:

throw 'ABC'; throw 123;
Code language: JavaScript (javascript)

Whenever the JavaScript reaches the throw operator, it stops the execution of the code immediately. To continue the code execution, you need to use the try...catch statement to catch the value that was thrown. See the following example:

try { throw 123; } catch (error) { console.log(error); // 123 } console.log('continue!'); // "continue!"
Code language: JavaScript (javascript)

In practice, you should use one of the error types as mentioned earlier as an error to throw, for example:

function add(a, b) { if (typeof a !== 'number') { throw TypeError('The first argument must be a number'); } if (typeof b !== 'number') { throw TypeError('The second argument must be a number'); } return a + b; } add('string', 1);
Code language: JavaScript (javascript)

Error

TypeError: The first argument must be a number
Code language: JavaScript (javascript)

Custom Error

You can create a custom error that inherits from a built-in error as follows:

function InvalidCallError(message) { this.name = 'InvalidCallError'; this.message = message; } InvalidCallError.prototype = Object.create(Error.prototype); InvalidCallError.prototype.constructor = Error;
Code language: JavaScript (javascript)

Then, you can throw the custom error as shown in this example:

throw new InvalidCallError('Invalid function call');
Code language: JavaScript (javascript)

Error

"Uncaught InvalidCallError: Invalid function call"
Code language: JSON / JSON with Comments (json)

In this tutorial, you have learned how to handle errors by using the JavaScript try...catch statement.

Was this tutorial helpful ?