What type of Exception
is thrown if the user enters a 0 for the
divisor?
An ArithmeticException
will be thrown when the division is attempted.
Here is a part of the program:
// Version 1 // try { System.out.print("Enter the numerator: "); num = scan.nextInt(); System.out.print("Enter the divisor : "); div = scan.nextInt(); System.out.println( num + " / " + div + " is " + (num/div) + " rem " + (num%div) ); } catch (InputMismatchException ex ) { System.out.println("You entered bad data." ); System.out.println("Run the program again." ); } catch (ArithmeticException ex ) { System.out.println("You can't divide " + num + " by " + div); } }
Here is some sample output:
C:\JavaSource>java DivisionPractice Enter the numerator: Rats You entered bad data. Run the program again. C:\JavaSource>java DivisionPractice Enter the numerator: 12 Enter the divisor: 6 12 / 6 is 2 rem 0 C:\JavaSource>java DivisionPractice Enter the numerator: 12 Enter the divisor: 0 You can't divide 12 by 0
Does that program really need to attempt the division and cause an Exception
?
Could an if
statement detect a potential division by zero before it happens?