Chapter 3. Exceptions

Few features of the Java language are as generally reviled and misunderstood as Java exceptions. Exceptions have to be declared as part of the signature of a method, and if an exception is declared as being thrown by a method, any code calling that method either needs to throw that same exception or needs to occur within a try block, and the calling method must include code that will catch the exception and deal with it. There are large numbers of programmers who hate this “extra” work and think that it makes their code messy and hard to read. Worse yet, they have to think about what could go wrong, and wrap their code calling anything that could throw an exception in a block. These blocks are uninteresting, and make it hard to remember what it is that the method is trying to do in the first place.

But exceptions in the Java language are definitely part of the good things about the language. Using exceptions correctly, your code can be easier to read. Using exceptions, your code can be more reliable. Using exceptions, your code can be easier to maintain. Those who object to the exception mechanism either don’t understand it, don’t realize what it can do, or are simply lazy twits who don’t care about writing reliable code.[10] In spite of evidence to the contrary, I like to think that there are very few in the third category. So in this chapter we will talk about exceptions for those in the first two groups, explaining how exceptions should be used and why this ...

Get Java: The Good Parts now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.