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 executed and then execution leaves the method.


Example

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("The program is now ending." );
     }

     System.out.println("Good-by" );
  }

}

If the user enters good data

  1. the try block executes successfully
  2. the finally block executes
  3. the program exits normally
Enter the numerator: 13
Enter the divisor  : 4
13 / 4 is 3 rem 1
The program is now ending.
Good-by

Now say the user enters a zero divisor:

  1. the try block starts to execute, but
  2. throws an ArithmeticException due to division by zero
  3. the ArithmeticException is caught and the error message is printed
  4. the finally block is executed
  5. the program exits normally
C:\JavaSource\> java FinallyPractice
Enter the numerator: 24
Enter the divisor  : 0
You can't divide 24 by 0
The program is now ending.
C:\JavaSource\> 

Now say the user enters bad data:

  1. the try block starts to execute, but
  2. throws an InputMismatchException when bad data is encountered
  3. the InputMismatchException is NOT caught
  4. the finally block is executed
  5. the program exits abnormally and throws the InputMismatchException to its caller, the run time system
  6. the run time system prints a stack trace
C:\JavaSource\> java FinallyPractice
Enter the numerator: 24
Enter the divisor  : zero
The program is now ending.
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:15)
C:\JavaSource\> 

QUESTION 20:

At what line number did the exception occur?


go to previous page   go to home page   go to next page