O'Reilly logo

Programming Scala by Alex Payne, Dean Wampler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Exceptions and the Alternatives

If nulls are the “billion dollar mistake” as we discussed in Option, Some, and None: Avoiding nulls, then what about exceptions? You can argue that nulls should never occur and you can design a language and libraries that never use them. However, exceptions have a legitimate place because they separate the concerns of normal program flow from “exceptional” program flow. The divide isn’t always clear-cut. For example, if a user mistypes his username, is that normal or exceptional?

Another question is where should the exception be caught and handled? Java’s checked exceptions were designed to document for the API user what exceptions might be thrown by a method. The flaw was that it encouraged handling of the exception in ways that are often suboptimal. If one method calls another method that might throw a checked exception, the calling method is forced to either handle the exception or declare that it also throws the exception. More often than not, the calling method is the wrong place to handle the exception. It is too common for methods to simply “eat” an exception that should really be passed up the stack and handled in a more appropriate context. Otherwise, throws declarations are required up the stack of method calls. This is not only tedious, but it pollutes the intermediate contexts with exception names that often have no connection to the local context.

As we have seen, Scala doesn’t have checked exceptions. Any exception can propagate to the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required