Example Program
Here is the example program modified to include a finally{} block.
The catch{} for the NumberFormatException
has been removed,
so these exceptions will cause a jump out of the try{} block
directly to the finally{} block.
import java.lang.* ;
import java.io.* ;
public class FinallyPractice
{
public static void main ( String[] a ) throws IOException
{
BufferedReader stdin =
new BufferedReader ( new InputStreamReader( System.in ) );
String inData; int num=0, div=0 ;
try
{
System.out.println("Enter the numerator:");
inData = stdin.readLine();
num = Integer.parseInt( inData );
System.out.println("Enter the divisor:");
inData = stdin.readLine();
div = Integer.parseInt( inData );
System.out.println( num + " / " + div + " is " + (num/div) );
}
catch (ArithmeticException ex )
{
System.out.println("You can't divide " + num + " by " + div);
}
finally
{
System.out.println("If the division didn't work, you entered bad data." );
}
System.out.println("Good-by" );
}
}
The user enters "Rats" and sees this output:
Enter the numerator:
Rats
If the division didn't work, you entered bad data.
Exception in thread "main" java.lang.NumberFormatException: Rats
at java.lang.Integer.parseInt(Integer.java:409)
at java.lang.Integer.parseInt(Integer.java:458)
at FinallyPractice.main(FinallyPractice.java:16)
|