How to Disable a Java Exception
When the Java Virtual Machine is running a program, many error conditions cause the runtime to raise (or, in Java parlance, "throw") an exception. Exceptions are Java objects in their own right; for example, there is an ArithmeticException class that gets thrown when the program attempts to divide by zero. Java programs can anticipate the possibility that an exception of a given type will occur, and transfer control to application-dependent, exception-handling code if and when the exception happens. You can write a handler for a Java exception -- if there is no handler, the uncaught exception will cause your program to abort immediately.
Instructions
-
-
1
Include the following line at the beginning of your Java code:
include java.lang.Exception;
-
2
Specify which exceptions your method can throw when declaring it, as in the following sample code:
public void mySwap(int[] sequence, int from, int to) throws ArrayIndexOutOfBoundsException {
int tmp;
tmp=sequence[from];
sequence[from]=sequence[to];
sequence[to]=tmp;
}
ArrayIndexOutOfBoundsException is an exception class pre-defined as part of the Java libraries.
-
-
3
Write a handler for that particular exception type whenever you call your method, as in the following example:
int[] samples={36,567,76,3536362,9}
try {
mySwap(samples,2,5);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("mySwap() threw exception");
}
The code following "catch" is the exception handler. It can do whatever your application needs to do to recover from that particular exception.
-
1