w3resource

JavaScript Program: Handling different types of errors with multiple catch blocks

JavaScript Error Handling: Exercise-8 with Solution

Write a JavaScript program that shows the use of multiple catch blocks to handle different types of errors separately.

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) {
    if (error instanceof TypeError) {
      console.log('TypeError:', error.message);
    } else {
      console.log('Error:', error.message);
    }
  }
}

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

Sample Output:

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

Note: Executed on JS Bin

Explanation:

In the above exercise,

  • The "divide_Numbers()" function takes two parameters x and y. Inside the function, we have a try block where we attempt to perform a division operation using the provided arguments.
  • Within the try block, there are two if conditions to validate the arguments. The first condition checks if x or y is not a number using the typeof operator. If either of them is not a number, we throw a TypeError using the throw statement with a custom error message.
  • The second condition checks if the divisor y is equal to zero. If it is, we throw a generic Error using the throw statement with a custom error message.
  • If both conditions are met, we proceed with the division operation and store the result in the result variable. We then log the result to the console.
  • If any error occurs within the try block, it is caught in the catch block. The catch block takes an error parameter representing the thrown error object. Inside the catch block, we use an if-else statement to determine the type of error.
  • If the error is an instance of TypeError, we log a message with the prefix 'TypeError:' followed by the error message. Otherwise, for other types of errors, we log a message with the prefix 'Error:' followed by the error message.

Next the "divide_Numbers()" function is called three times with different arguments. The first call with 20 and '4' results in an invalid divisor since the second argument is not a number. The second call with 20 and 4 is a valid division and prints the result. The third call with 20 and 0 throws an error due to division by zero.

Flowchart:

Flowchart: Handling different types of errors with multiple catch blocks.

Live Demo:

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


Improve this sample solution and post your code through Disqus

Error Handling Exercises Previous: Catching and handling RangeError with Try-Catch.
Error Handling Exercises Next: Handling URIError with Try-Catch block for invalid URI decoding.

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.