w3resource

JavaScript Program: Error handling and cleanup with the try-catch-finally statement

JavaScript Error Handling: Exercise-10 with Solution

Write a JavaScript program that demonstrates the use of the 'try-catch-finally' statement to catch and handle an error, and then execute some cleanup code in the 'finally' block.

Sample Solution:

JavaScript Code:

function divide_Numbers(x, y) {
  try {
    if (typeof x !== 'number' || typeof y !== 'number') {
      throw new TypeError('Invalid arguments. Both arguments should be numbers.');
    }

    if (y === 0) {
      throw new Error('Invalid divisor. Cannot divide by zero.');
    }
    const result = x / y;
    console.log('Result:', result);
  } catch (error) {
    console.log('Error:', error.message);
  } finally {
    console.log('Cleanup code executed.');
  }
}

// Example:
divide_Numbers(10, 2);  //  Valid division
divide_Numbers(10, 0); // Division by zero
divide_Numbers(10, '2'); // Invalid divisor

Sample Output:

"Result:"
5
"Cleanup code executed."
"Error:"
"Invalid divisor. Cannot divide by zero."
"Cleanup code executed."
"Error:"
"Invalid arguments. Both arguments should be numbers."
"Cleanup code executed."

Note: Executed on JS Bin

Explanation:

In the above exercise -

  • The function "divide_Numbers()" takes two arguments, x and y. This function performs a division operation and handle potential errors.
  • Inside the try block, the code checks if both x and y are numbers using the typeof operator. If either of them is not a number, a TypeError is thrown with the message 'Invalid arguments. Both arguments should be numbers.'.
  • Next, check to see if the divisor y is equal to zero. If it is, an Error is thrown with the message 'Invalid divisor. Cannot divide by zero.'.
  • If no errors occur, the code performs the division operation x / y and logs the result to the console using console.log('Result:', result).
  • If an error is thrown within the try block, execution jumps to the catch block. In the catch block, the error object is caught in the error parameter. Its message is logged to the console using console.log('Error:', error.message).
  • Regardless of whether an error occurred or not, the code in the "finally" block is always executed. In this case, the "finally" block contains the statement console.log('Cleanup code executed.'), which logs the message 'Cleanup code executed.' to the console.

Flowchart:

Flowchart: Catching and handling RangeError with Try-Catch.

Live Demo:

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


Improve this sample solution and post your code through Disqus

Error Handling Exercises Previous: Handling URIError with Try-Catch block for invalid URI decoding.
Error Handling Exercises Next: Catching and handling EvalError 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.