w3resource

JavaScript Program: Catching and handling ReferenceError with the try-catch Block

JavaScript Error Handling: Exercise-12 with Solution

Write a JavaScript program that uses a try-catch block to catch and handle a 'ReferenceError' when accessing an undefined variable.

Sample Solution:

JavaScript Code:

function access_Variable() {
  try {
    console.log(undefinedVariable);
  } catch (error) {
    if (error instanceof ReferenceError) {
      console.log('ReferenceError:', error.message);
    } else {
      console.log('Error:', error.message);
    }
  }
}

// Example:
access_Variable();

Sample Output:

"ReferenceError:"
"undefinedVariable is not defined"

Note: Executed on JS Bin

Explanation:

In the above exercise,

  • Inside the try block, the console.log(undefinedVariable) statement throws a ReferenceError because the variable does not exist. The code then jumps to the catch block.
  • In the catch block, the error object is caught in the error parameter. The code checks if the error is an instance of ReferenceError using the instanceof operator. If it is, the error message is logged to the console as 'ReferenceError: <error message>'. If it's a different type of error, the error message is logged as 'Error: <error message>'.
  • In the example calling access_Variable() triggers a ReferenceError because undefinedVariable is not defined. The error message, 'ReferenceError: undefinedVariable is not defined', is logged to the console.

Flowchart:

Flowchart: Catching and handling RangeError with Try-Catch.

Live Demo:

See the Pen javascript-error-handling-exercise-12 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Error Handling Exercises Previous: Catching and handling EvalError with the try-catch Block.
Error Handling Exercises Next: Catching and handling JSON string SyntaxError.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.