I’ve read about and experimented with the Scala 2.9 try…catch feature, and it has me thinking about possibilities. What would I actually use it for other than saving a couple of lines of code?
I’ve read about and experimented with the Scala 2.9 try…catch feature, and it has
Share
The use case is to be able to have generic error handling throughout your application. Let’s say you want to handle all
FileNotFoundExceptions in your application by sending an e-mail to an administrator. Previously, you’d have to do it like this:Now you just do:
This also has the nice advantage that you can link several such exception handlers using the
orElsemethod on partial functions:And then just use that everywhere where you need file exception handling. Such an error handler can be dynamically combined based on the configuration file for the application, for example. This is much less cumbersome than pattern matching everywhere and calling the correct handler.
One useful thing which could be pimped on top of partial functions is the
andAlsooperator, which acts as a sequencing operator on two partial functions. This would be useful when you want to do some error handling specific to a particular try-catch block after having done the generic error handling.And then you can do this:
I guess you could play further with the exact semantics and the meaning (and the name) of
andAlso.