package dividedbyzero;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* @author HP
*/
public class Dividedbyzero {
public static int quo(int num,int denum)
throws ArithmeticException
{
return num/denum;
}
public static void main(String[] args) {
Scanner obj=new Scanner(System.in);
boolean conlop=true;
do{
try{
System.out.print("please enter integer");
int num=obj.nextInt();
System.out.print("please inter");
int denum=obj.nextInt();
int result=quo(num,denum);
System.out.printf("%nRESULT : %d /%d = %d%n",num,denum,result);
conlop=false;
}
catch(InputMismatchException | ArithmeticException a){
System.err.printf("%n Exception : %s%n",a);
obj.nextLine();
System.out.printf("you mustt num please enter again");
}
}while(conlop);
}
}

- 41
- 5
-
So what's the question? You can do that since Java 7. There is no compilation error if you are using Java 7 or above – Ivan May 13 '19 at 13:38
-
Have you tried throwing both exceptions to see if they are caught? – Steve Smith May 13 '19 at 13:42
3 Answers
You can do it. It will catch the error. You might want to use different catch blocks thought. In your program, when the ArithmeticException is caught, the same message is printed to the user as for the InputMismatchException. Also, we like to go from the more specific kind of exception to the less specific kind of exception.
catch(ArtithmeticException e){
//some code
}
catch(Exception e){
//some code
}
In this case, I would use the InputMismatchException in the first catch, then catch the ArithmeticException.
-
the question is to use the catch block one time and use two Exception – behram shah May 26 '19 at 06:57
I believe this is what you are looking for handling two different exception in a single catch block , It could be achieved like this , hope you know about all the checked exception that could possibly occur.
catch(Exception ex){
if(ex instanceOf InputMismatchException )
//Do 1....
else if(ex instanceOf ArithmeticException)
//Do 2...
else
throw ex;
}

- 365
- 3
- 9
Short answer: Yes, you can catch multiple exceptions in one catch.
Long answer: This was added starting java 7 you can pip different exceptions in one catch, however you should pay attention to the order of exceptions.

- 2,855
- 1
- 25
- 37

- 1
- 1