Looking for JavaScript try catch example?
Try-catch and finally block is a crucial part of JavaScript programming.

Welcome to Letstaclewe help students with programming/coding hurdles. Here is a quick tutorial on JavaScript try-catch with examples.

What is try-catch, throw and finally in JavaScript?

These are programming statement which lets you handle the program flow if any error happens.

try– We put the test code inside the try statement block.

catch– if the test code fails, the catch block helps to handle the error.

throw– Let’s you make custom errors.

finally– This block executes at the end of the try catch regardless the test code throws an error or not.

Thus, if any error occurs JavScript execution will stop and generate an error message. In technical terms, it means that JavaScript will throw an exception.

An error can be of two types-

  1. Coding or programming error made by the programmer.
  2. Wrong input or any other error.

Syntax of JavaScript try catch and finally

try{

  // test code goes here

}catch(err){

  // if test code throws error 
  // catch it and display the error

}finally{

  // put additional code 
  // which does not depends on the test code
  // or display a message simply

}

Before proceeding with the JavaScript try catch example, Please note that the catch block receives an error object. These error objects are built-in and provide an error message if any error occurs.

The error object contains two useful properties-

  1. name      – returns an error name
  2. message – returns an error message of type string

Error name you might get in the catch block

EvalError            – An error has occurred in the eval() function
RangeError        – A number “out of range” has occurred
ReferenceError – An illegal reference has occurred
SyntaxError       – A syntax error has occurred
TypeError          – A type error has occurred
URIError             – An error in encodeURI() has occurred

Code Examples of JavaScript Try Catch

1. Example : JavaScript TypeError

In this try-catch example, we have deliberately passed a number to a function which only accepts a string.


try {
  let num = 0;
  process.stdout.write(num);
} catch (err) {
  console.log(
    "Error Name: " + err.name + "\n" + 
    "Error Message: " + err.message);
} finally {
  console.log("---- End of execution----");
}

Output

Thus, you see the exception on the console as TypeError along with the message.

TypeError JavaScript example

TypeError JavaScript example


2.Example : ReferenceError

The reference occurs when a variable is undefined and we try to use that variable. in this example we are trying to log a variable ‘num‘ which is not defined.

try {
  console.log(num);

} catch (err) {
  console.log(
    "Error Name: " + err.name + "\n" + 
    "Error Message: " + err.message);
}

Output

Error Name: ReferenceError
Error Message: num is not defined

3.Example: URIError

A bad formatted URL throws a URIError


try {
  decodeURI("%");  
} catch (err) {
  console.log(
    "Error Name: " + err.name + "\n" + 
    "Error Message: " + err.message);
}

Output

Error Name: URIError
Error Message: URI malformed

4.Example: RangeError

When a value is out of range to a specific function or any user-defined block of code. Here we are using JavaScript throw as to show our own error message, making the use of object RangeError.


let num =-1;
try {
 if(num<0){
  throw new RangeError("number is negative");
 } 
} catch (err) {
  console.log(
    "Error Name: " + err.name + "\n" + 
    "Error Message: " + err.message);
}

Output

Error Name: RangeError
Error Message: number is negative

5.Example: SyntaxError

Finally, Syntax Error and Eval was combined in one.  Here is an example of a syntax error where we are trying to evaluate a string with no meaningful arithmetic.


try {
  eval('Hey Hi!!');
} catch (err) {
  console.log(
    "Error Name: " + err.name + "\n" + 
    "Error Message: " + err.message);
}

Output

Error Name: SyntaxError
Error Message: Unexpected identifier

✌️ Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed