Runtime Exceptions
Runtime exceptions generally occur as a result of coding bugs. By far the most common type of runtime exception you will encounter is the NullPointerException. This occurs when you attempt to access a field or method on an object reference that has a null value, i.e. it is not a reference to an object on the heap.
The following is a simple program that generates a NullPointerException:
package exceptions;
public class Runtime {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
StringBuffer sb2 = null;
appendWorld(sb);
appendWorld(sb2);
}
private static void appendWorld(StringBuffer sb) {
sb.append(" World");
}
}
If you run this program it will generate the following output:
Exception in thread "main" java.lang.NullPointerException
at exceptions.Runtime.appendWorld(Runtime.java:11)
at exceptions.Runtime.main(Runtime.java:7)
This is referred to as a stack trace – it is a dump of the call stack of the program when the exception occurred. Stack traces are the most common mechanism available for diagnosing an exception after the fact.
All exceptions contain stack traces, not just RuntimeExxception.
The first line of the stack trace tells you the type of exception that has occurred and the thread that it occurred in. This is a single threaded program, but when I introduce multi-threading you will see why this is important.
The remaining lines of the stack trace show the call-stack of the program at the point the error occurred. You always read stack traces from top to bottom. The first line of the stack-trace is the line that the exception occurred on (line 11 of the Runtime class). The next line tells you the line in the program that called this method (line 7 in the Runtime class).
In real-world programs stack traces can become very long, sometimes 20 or 30 levels deep, but usually the first couple of lines are sufficient to understand what was happening when the exception occurred.
Once you understand the context of the exception you can quickly determine what has happened. If you look at line 11 of Runtime, the only reason that this exception could have occurred would be if sb was null. You can therefore determine that at line 7 of the Runtime class you are passing a null StringBuffer to appendWorld.
You will notice that methods do not need to declare the fact that they throw runtime exceptions. The reason for this is that the list of possible runtime exceptions that could conceivably be thrown by a method could be large (virtually all methods could generate a NullPointerException).
The fact that you do not have to handle runtime exceptions leads some programmers to favor them over checked exceptions – even in cases where checked exceptions are more appropriate. Try not to fall into this trap – if an exception represents a business rule violation, rather than a coding bug, it should not be a RuntimeException.
I mentioned earlier that RuntimeExceptions such as NullPointerExeption should not be handled. The reason for this is that they are bugs: you never should have passed a null StringBuffer to the appendHello method. Instead of adding exception-handling logic, therefore, you should change your code. For instance, you may decide that the best way to handle this exception is for appendWorld to check whether it has been passed a null reference:
private static void appendWorld(StringBuffer sb) {
if (sb != null) {
sb.append(" World");
}
}
The following are the most common RuntimeExceptions you will encounter in Java:
IllegalArgumentException: this occurs when an invalid value is passed to a method. For instance, if the method only accepts positive numbers, it may throw an IllegalArgumentException if it is passed a negative number.
IllegalStateException: this indicates that the method has been invoked at an illegal time. I could have used this exception instead of UninitializedException earlier, because I was essentially stating that an invocation had occurred at the wrong time (before the object was initialized).
ArrayIndexOutOfBoundsException: this occurs when you access an index in an array that is greater than the length of the array.
ClassCastException: this occurs when you cast an object to be an invalid type: for instance if you cast a String to a StringBuffer.
UnsupportedOperationException: as its name suggests, this is thrown when an operation is not supported. For instance, if a method required by an interface has not been implemented yet it could throw an UnsupportedOperationException.
ArithmeticException: this most commonly occurs when you divide an integer by 0.
There is nothing to stop you throwing these exceptions in your own code. In fact, before creating your own specific exception types it always makes sense to find out if an existing exception type exists in Java.