Java Reference
In-Depth Information
public static void main(String[] args) {
for (int i = 0; i >= 0; i++) {
myStrings .add("String number: " + i);
}
}
}
Depending on your machine and settings, this will sooner or later throw a java.lang.
OutOfMemoryError . The problem is the termination condition of the for loop. The iterator, int i , is ini-
tialized with a value of 0 and increments by 1 with each loop. The loop is supposed to terminate when the
value of i goes below 0, but it will never reach this condition because it is increasing, not decreasing. This
might be easy to spot here, but if your termination condition is dependent on a variable or method result,
you might not immediately see where infinite looping is possible. If you encounter an OutOfMemoryError ,
take a look at object creation events, especially inside loops or recursive method calls.
public class EndlessMethodCall {
public static void main(String[] args) {
printMe ();
}
public static void displayMe(){
printMe ();
}
public static void printMe(){
displayMe ();
}
}
Running this program will almost immediately cause a java.lang.StackOverflowError exception
to be thrown. The two methods call each other back and forth without end. If you experience this
kind of error, you should first look into method calls to see whether you've unintentionally created
an infinite loop. A related problem occurs when a method calls itself, something referred to as recur-
sion. Recursion is often a valuable tool, as long as there is an appropriate stopping condition to keep
it from calling itself infinitely, or until an exception is thrown, of course.
It is impossible to cover every possible exception in this topic, but with this foundation, you should be
able to begin to deal with them appropriately. If you encounter other exceptions as you are program-
ming, searching online for the name of the exception will help you understand why it is occurring. The
techniques demonstrated in the next section will help you deal with all kinds of exceptions.
catching exceptions
Now that you've been introduced to the three main error categories and some common exceptions,
it's time to start learning how to handle them when you do encounter them. The first step is a new
structure called a try/catch block. This essentially allows you to try executing a piece of code to
see if an exception is thrown. If none is thrown, the program will proceed normally, but if one is
thrown, you can catch it and specifically indicate what should be done next. This prevents your pro-
gram from crashing and at least allows you to recover some information before it terminates.
 
Search WWH ::




Custom Search