Akila Adithya Akila Adithya - 4 years ago 82
Java Question

Catching Multiple Type of Exceptions

How can I Display these different messages according to the different exception?? How to identify the exception and how can I declare it inside the if statement???

Here is my code,

import java.util.* ;
import java.util.Scanner;

class Cal{
public static void main (String args[]){
int a;
int b;
Scanner sc=new Scanner(System.in);
try{
System.out.println("Enter first number:");
a=sc.nextInt();
System.out.println("Enter second number:");
b= sc.nextInt();
System.out.println("Your result:" +(a/b));
}
catch(InputMismatchException| ArithmeticException e){
if()
System.out.println("please enter valid number");
else
System.out.println("you cannot divide any number by zero!");
}

Answer Source

As @Nic posted, you can and should generally use multiple catch blocks like this:

catch(InputMismatchException  e) {
  System.out.println("please enter valid number");
} catch(ArithmeticException e) {
  System.out.println("you cannot divide any number by zero!");
}

This is the best way when you have different behaviors for different types of Exception. However, if that does not work for you you can do something like this:

catch(InputMismatchException | ArithmeticException e){
    if(e instanceof InputMismatchException)
      System.out.println("please enter valid number");
    else
      System.out.println("you cannot divide any number by zero!");
}

One reason you might want to use the second pattern is if most of your exception handling behavior is the same (closing resources, writing to a log file, etc.) but only the message to display is different.

One other (probably cleaner) solution would be to use multiple catch blocks and a single finally block to handle all shared actions. However, your question asks how to do it using one catch block, so the above should work for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download