Stack Trace

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

No. If an Exception is thrown in the try block but not caught, then the finally() block is exectued and then execution leaves the method.

Stack Trace

Here is the example program modified to include a finally{} block. The catch{} for InputMismatchException has been removed. Now these Exceptions cause a jump out of the try{} block directly to the finally{} block.

import java.util.* ;

public class FinallyPractice
{
  public static void main ( String[] a ) 
  {
    Scanner scan = new Scanner( System.in  );
    int    num=0, div=0 ;

    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." );
     }
   }
}

If the user enters good data, the finally{} block is exectued:

Enter the numerator: 13
Enter the divisor  : 4
13 / 4 is 3 rem 1
If something went wrong, you entered bad data.

If the user enters bad data, the finally{} block is exectued, but the Exception (due to the bad data) is passed up:

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)

QUESTION 17:

Where did the last 6 lines of output come from?