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 some of the most common exceptions in Java programs caused by bugs. This chapter differs somewhat from the others, as we will concentrate on the effects 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 a superclass. Exceptions covered in this chapter are shaded.
figure

It’s important to understand that exceptions are your friends, not enemies. Many programmers dislike exceptions, but they are there to help you 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. One more important exception, ConcurrentModificationException, will be covered separately when we will talk about collections in chapter 8.

5.1 Mistake 41: NullPointerException

5.1.1 Avoiding nulls and defensive checks

5.1.2 Using Optional instead of null

5.1.3 Nullity annotations

5.2 Mistake 42: IndexOutOfBoundsException

5.3 Mistake 43: ClassCastException

5.3.1 Explicit cast

5.3.2 Generic types and implicit casts

5.3.3 Different class loaders

sitemap