Part- 5
Catch all exception handler
• Since all exceptions are subclasses of
Exception,
– To catch all exceptions, one uses the
catch-all exception handler with
Exception as the type
catch (Exception e) {
//catch block
}
• Since one exception is handled by at most one
catch block,
– if there is more than one catch block,
– and a catch-all,
• then the catch-all error handler must appear last
– for the first catch block which fits the
exception will be executed.
• Similarly, if there are two catch blocks one
involving a base type and one a derived type,
– then the catch block with base type must
appear last
– since a base type will fit a derived type,
but not vice versa.
Exceptions: Miscellaneous
• Try blocks may be nested.
– In this case, if the first try block does not
have an appropriate handler for the
exception, the exception will be passed
to the outer block, and so on.
– The exception can be handled by both
inner and outer catch block, by making
the inner catch block rethrow what it has
caught.
• A finally clause may be associated with each try
block, and this is guaranteed to execute.
– The JVM achieves this by checking all
possible exits to the try block.
Program:-
import java.io.*;
public class NestedCatch
{
public static void main(String args[])
{
int a;
int b;
try
{
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”);
throw e; //rethrow
}
catch (IOException i)
{
System.out.println (“Caught i/o
exception”);
}
finally
{
System.out.println (“Exiting inner try”);
}
}
catch(Exception e)
{
System.out.println (“Caught something”);
}
System.out.println (“Program exit”);
}
}
• input:
a=2
b=2
• output:
Exiting inner try
Program exit
• input:
a=*
• output:
Exiting inner try
Caught something
Program exit
-------------- <<<Part- 4 ----------------------------------
No comments:
Post a Comment