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.

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

5.4 Mistake #44. StackOverflowError

5.4.1 Deep but finite recursion

5.4.2 Infinite recursion

5.5 Summary

sitemap