5 Exception Handling
5 Exception Handling
Exception Error
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached.");
}
}
}
/* Try statements can be implicitly nested via
public static void main(String args[])
calls to methods. */ {
class MethNestTry { try {
static void nesttry(int a) { int a = args.length;
try { // nested try block
/* If one command line arg is used, then an /* If no command line args are
divide-by-zero exception will be generated present, the following statement will
by the following code. */ generate a divide-by-zero exception. */
if(a==1) a = a/(a-a); // division by zero int b = 42 / a;
/* If two command line args are used then System.out.println("a = " + a);
generate an out-of-bounds exception. */
if(a==2) {
nesttry(a);
int c[] = { 1 };
} catch(ArithmeticException e) {
c[42] = 99; // generate an out-of-bounds
exception System.out.println("Divide by 0: "
+ e);
}
}
} catch(ArrayIndexOutOfBoundsException
e) { }
System.out.println("Array index out-of- }
bounds: " + e);
}
}
throw Keyword
w Using “throw” statement
n It is possible for your program to throw an
exception explicitly.
n General form: throw ThrowableInstance;
l Here ThrowableInstance must be an object of type
Throwable or a subclass of Throwable.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // re-throw the exception
} Caught inside demoproc.
} Recaught: java.lang.NullPointerException: demo