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:
// Define a function named access_Variable that attempts to access an undefined variable
function access_Variable() {
// Try block to attempt accessing the undefined variable and handle potential errors
try {
// Attempt to log the value of an undefined variable to the console
console.log(undefinedVariable);
} catch (error) {
// Catch block to handle errors
// Check if the error is an instance of ReferenceError
if (error instanceof ReferenceError) {
// If the error is a ReferenceError, log the error message to the console
console.log('ReferenceError:', error.message);
} else {
// If the error is not a ReferenceError, log the error message to the console
console.log('Error:', error.message);
}
}
}
// Example:
// Call the access_Variable function to demonstrate accessing an undefined variable
access_Variable();
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/error-handling/javascript-error-handling-exercise-12.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics