Consider the following C-like code for handling error conditions:
if (function1()) // boolean return type indicates success/failure
if (function2())
if (function3())
print("all functions OK");
else
print("error function3");
else
print("error function2");
else
print("error function1");
Or this code:
function1(&error); // call-by-reference error code indicates success/failure
if (!error) {
function2(&error);
if (!error) {
function3(&error):
if (!error)
print("all functions OK");
}
}
if (error)
print("error: %d",error);
Instead of cascading ``if'' statements, write code that assumes good behavior:
function1(); function2(); function3(); // handle any possible errors
That is the point of Exception handling in Java
Note that printing may not be a suitable method for ``handling'' error events
A function may not be able to handle an event, and then must pass it along
Exceptions [20]
class MyException extends Exception {
public MyException() { super(); }
public MyException(String s) { super(s); }
}
class MyOtherException extends Exception {
public MyOtherException() { super(); }
public MyOtherException(String s) { super(s); }
}
class MySubException extends MyException {
public MySubException() { super(); }
public MySubException(String s) { super(s); }
}
public class Throwtest {
public static void main(String argv[]) {
int i;
try { i = Integer.parseInt(argv[0]); }
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Must specify an argument");
return;
}
catch (NumberFormatException e) {
System.out.println("Must specify an integer argument");
return;
}
a(i);
}
}
Exceptions [21]
public static void a(int i){
try b(i);
catch (MyException e) {
if (e instanceof MySubException)
System.out.print("MySubException: ");
else
System.out.print("MyException: ");
System.out.println(e.getMessage());
System.out.println("Handled at point 1");
}
}
public static void b(int i) throws MyException {
int result;
try {
System.out.print("i="+i+" ");
result = c(i);
System.out.println("c(i)="+result);
}
catch (MyOtherException e) {
System.out.println("MyOtherException: "+e.getMessage());
System.out.println("Handled at point 2");
}
}
public static int c(int i) throws MyException, MyOtherException {
switch (i) {
case 0 : // processing resumes at point 1 above
throw new MyException("input too low");
case 1 : // processing resumes at point 1 above
throw new MySubException("input still too low");
case 99: // input resumes at point 2 above
throw new MyOtherException("input too high");
default: return i*i;
}
}