Search This Blog

27 June, 2011

Exception handling: Java specific part-3


Part - 3
Exceptions: multiple catch blocks
• Catch is not called: program execution is
transferred to it.
– if no exception occurs, then the catch
block will NOT execute.
• There may be more than one catch block.
– Each catch block handles one type of
exception .
– But only that catch block will be
executed which matches the type of the
exception generated.
• Thus, if we rewrite the previous program, so that
– there are two catch blocks:
– one which handles arithmetic exceptions.
– and one which handles i/o exceptions,
– and if an integer is incorrectly entered,
– then the exception will NOT be caught,
and an abnormal program termination
will occur .


Program:-

import java.io.*;
public class MultipleCatch
{
public static void main(String args[])
{ int a;
int b;
try
{
System.out.println (“a = ”);
DataInputStream in = new
DataInputStream(System.in);
String inString = in.readLine();
a = Integer.parseInt (inString);
System.out.println (“b = ”);
b = Integer.parseInt (in.readLine());
int c = a/b;
}
catch(ArithmeticException e)
{
System.out.println (“Caught Arithmetic"+
“exception”);
}
catch (IOException i)
{ System.out.println (“Caught i/o”+
“exception”);
}
System.out.println (“Program exit”);
}
}




• Case 1: input:
a=2
b=3
• output: Program exit
• Case 2: Inputa=2
b=0
• Output:
Caught Arithmetic Exception
Program exit
• Case 3: input: a= *
• output:
java.lang.NumberFormatException: *
at java.lang.Integer.parseInt(Integer.java:231)
at java.lang.Integer.parseInt (Integer.java:278)
at MultipleCatch.main (MultipleCatch.java:15)
• Case1: no catch block is executed, since no
exception is thrown.
• Case 2: the first catch block is executed, since
an ArithmeticException is thrown.
• Case 3: a NumberFormatException is thrown but
there is no matching catch block. Hence the
program terminates.


<<<-Part - 2      ------------------------   Part - 4 >>>    


No comments:

Post a Comment

Meetme@