How to Exit Out of a Program If Something Is in Error in Java
The Java programming language supports a flexible scheme for handling error conditions (called "exceptions" in this context) that arise during program execution. A program can declare part of its own code as a handler for a particular type of exception (e.g., division by zero). If that exception is raised at runtime, Java will transfer control to the handler. If no handler for that exception has been declared, the Java program will exit automatically.
Instructions
-
-
1
Specify the exceptions your methods can throw, as in the following example:
public void swapArrayElements(int[] numbers, int index1, int index2) throws ArrayIndexOutOfBoundsException {
int temp;
temp=numbers[index1];
numbers[index1]=numbers[index2];
numbers[index2]=temp;
}
Without throws ArrayIndexOutOfBoundsException, this would be an illegal method declaration---every method must handle or throw (that is, propagate to its caller) any exception it can generate.
-
2
Handle the error condition as in the following example:
try {
swapArrayElements(myNumbers,20,13);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Method threw exception, no problem--continuing");
}
The "println" command will get executed whenever swapArrayElements throws the exception; this is known as "catching" the exception.
-
-
3
Leave error conditions unhandled if you want the program to exit when they happen, as in the following simple method invocation:
swapArrayElements(myNumbers,20,13);
If swapArrayElements throws an exception, the Java program will stop.
-
1