I tried to handle ArithmeticException by throwing an exception in the method and by handling with try and catch block in the caller method. But the program still shows ArithmeticException error.
import java.util.Scanner;
public class QuotientWithException{
public static int quotient(int n1,int n2){
if(n2==0)
throw new ArithmeticException("Divisor cannot be zero");
return n1/n2;
}
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter two integers:");
int n1=input.nextInt();
int n2=input.nextInt();
try{
int result=quotient(n1,n2);
System.out.println(n1 "/" n2 " is " result);
}
catch(ArithmeticException ex){
System.out.println("Exception: an integer cannot be divided by zero");
}
System.out.println("Execution continues ...");
}
}
Input
Enter two Integers:3 0
Output
Thread [main] (Suspended (exception ArithmeticException)) (out of synch)
QuotientWithException.main(String[]) line: 19 (out of synch)
CodePudding user response:
"Suspended" implies you're running your code using a debugger or similar functionality that is catching the exception and suspending the program run. If you run your code without a debugger, it should work as expected.