What is the best way to determine all the exceptions that can be thrown by a specific library function in Scala in order for client code to decide whether to handle the exceptions?
The fact that Scala has no checked exceptions is convenient, but I would still like to know what the possible exceptional events are that code should take into account when using a specific function.
Scala docs for libraries, in general, do not seem to document exceptions.
How are Scala users ensuring that their client code is taking into account the various exceptional events thrown by library functions?
Any library method that can take a function argument can throw any exception at all:
List(1).map(_ => throw new SomeExceptionIJustInvented)
Unfortunately, this means that, in the absence of a sophisticated compiler-based exception-tracking system, it is up to the programmer to understand which exceptions might be generated on the basis of library documentation and experience.
If it is very important to write code that is robust to exceptions, the best way to go is to catch all exceptions from relatively large blocks of code. Make sure you only catch Exception, not all throwables, since you probably can't do anything sane with an out of memory error. So:
try {
// Various stuff
}
catch {
case e: Exception => // Handle the case where stuff fails
}
Fortunately, Java libraries explicitly say what they're going to throw, and Scala libraries almost always throw very little and instead pass back Option or Either or have some other way of notifying you when something failed beyond throwing an exception. Scala libraries that use Java libraries are sometimes a bit opaque, however. (For example, if you're doing IO, it's a pretty safe bet that IOException could get thrown.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With