Enter the numerator: rats If something went wrong, you entered bad data. Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at FinallyPractice.main(FinallyPractice.java:13)
The try{}
block threw a InputMismatchException
,
but there was no catch{}
block for it.
So: (1) the finally
block executed, and then
(2) the Exception
was thrown to the caller (in this case the Java run time system),
which (3) printed the last six lines.
The last six lines are called a stack trace. Later you will see how to print them without stopping the program. Here is a section of the program:
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 (ArithmeticException ex ) { System.out.println("You can't divide " + num + " by " + div); } finally { System.out.println("If something went wrong, you entered bad data." ); } System.out.println("Good-by" );
Here are some further examples:
Example 1:
Enter the numerator: 26 Enter the divisor : 4 26 / 4 is 6 rem 2 If something went wrong, you entered bad data. Good-by
Example 2:
Enter the numerator: 26 Enter the divisor : 0 You can't divide 26 by 0 If something went wrong, you entered bad data. Good-by
Example 3:
Enter the numerator: 26 Enter the divisor : Zero If something went wrong, you entered bad data. Exception in thread "main" java.util.InputMismatchExceptio at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at FinallyPractice.main(FinallyPractice.java:15)