w3resource

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

JavaScript Error Handling: Exercise-11 with Solution

Write a JavaScript program that uses a try-catch block to catch and handle an 'EvalError' when evaluating an invalid expression.

Sample Solution:

JavaScript Code:

function evaluate_Expression(exp) {
  try {
    const result = eval(exp);
    console.log('Result:', result);
  } catch (error) {
    if (error instanceof EvalError) {
      console.log('EvalError:', error.message);
    } else {
      console.log('Error:', error.message);
    }
  }
}

// Example:
evaluate_Expression('30 + 30'); // Valid expression
evaluate_Expression('3 +'); // Invalid expression

Sample Output:

"Result:"
60
"Error:"
"Unexpected end of input"

Note: Executed on JS Bin

Explanation:

In the above exercise -

The "evaluate_Expression()" function takes an expression as a parameter and evaluates it using the "eval()" function.

  • Inside the try block, the code uses eval(exp) to evaluate the provided expression. The result is stored in the result variable.
  • If the expression is valid and can be successfully evaluated, the result is logged to the console using console.log('Result:', result).
  • If an error occurs during evaluation, the code jumps to the catch block.
  • Inside the catch block, the error object is caught in the error parameter.
  • The code checks if the error is an instance of EvalError using the instanceof operator.
  • If it is, the error message is logged to the console as 'EvalError: <error message>'.
  • If it's a different type of error, the error message is logged as 'Error: <error message>'.

Finally evaluate_Expression('30 + 30') returns a valid expression, '30 + 30', which results in 60 being logged to the console.

Next evaluate_Expression('3 +'), returns an invalid expression missing an operand. This causes an EvalError to be thrown. The error message, 'Unexpected end of input', is logged to the console.

Flowchart:

Flowchart: Catching and handling RangeError with Try-Catch.

Live Demo:

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


Improve this sample solution and post your code through Disqus

Error Handling Exercises Previous: Error handling and cleanup with the try-catch-finally statement.
Error Handling Exercises Next: Catching and handling ReferenceError with the try-catch Block.

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.