5 Common exceptions
This chapter covers
- Ways to avoid NullPointerException in Java programs
- Which mistakes cause IndexOutOfBoundsExceptions
- Different reasons for ClassCastException
- Finite and infinite recursion in Java
In this chapter we discuss the most common virtual machine exceptions that happen in Java programs due to bugs. This chapter differs somewhat from the others, as we will concentrate on the effect of the bugs, rather than their causes.
All the exception classes in Java inherit a single Throwable
class. Any exception can be thrown explicitly via a throw
statement. Some exceptions can be thrown by the virtual machine itself. Here, we will mainly speak about such exceptions. Figure 5.1 shows the hierarchy of exceptions covered in this chapter.
Figure 5.1 Hierarchy of exception classes. All Java exceptions inherit Throwable
, and many of them have Exception
, Error
or RuntimeException
as superclass. Exceptions covered in this chapter are shaded.
The common thing to understand about exceptions is that exceptions are your friends, not enemies. Many programmers dislike exceptions, but they are there to help you to write programs without bugs. It’s much better to have an exception as early as possible instead of continuing the execution of your program in an incorrect state, which may cause much more severe consequences like data loss or a security breach.