This is a code sample. If I was to enter numerator: 5 and Denominator: 0
I get an exception like this:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionHandling.DivideByZeroExceptions.quotient(DivideByZeroExceptions.java:10)
at ExceptionHandling.DivideByZeroExceptions.main(DivideByZeroExceptions.java:22)
I know I have to include ( throws Arithmetic Exception )
But, How would I know that I need to use a inputMismatchException?
// Try DivideByZeroExceptions
public class DivideByZeroExceptions {
public static int quotient(int numerator, int denominator) {
return numerator / denominator;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer numerator: ");
int numerator = input.nextInt();
System.out.println("Please enter an integer denominator: ");
int denominator = input.nextInt();
int result = quotient(numerator, denominator);
System.out.printf("\nResult: %d / %d = %d\n", numerator, denominator,
result);
}
}
Not sure exactly what your asking about inputMismatchException, but this is what you should do:
IllegalArgumentExceptionextendsRuntimeException, not justException. As such, it will simply stop execution of the thread after it occurs, so it doesn’t need to be caught/thrown (of course you can still catch it outside the method in order to prevent the Thread from stopping).