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.
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
try block executes successfullyfinally block executesEnter 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:
try block starts to execute, butArithmeticException due to division by zeroArithmeticException is caught and the error message is printedfinally block is executedC:\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:
try block starts to execute, butInputMismatchException when bad data is encounteredInputMismatchException is NOT caughtfinally block is executedInputMismatchException to its caller, the run time system
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\>
At what line number did the exception occur?