I've been reading up on how to properly handle (Option
, Try
and Either
) and define exceptions in Scala.
My question is: do exception hierarchies make sense in Scala? For example, we currently have a Scala project implementing something like:
class ServiceException(msg: String) extends Exception(msg)
class StorageServiceException(msg: String) extends ServiceException(msg)
class StorageServiceNotAvailableException(msg: String)
extends StorageServiceException(msg)
Is there an idiomatic way of defining such a hierarchy? Or maybe this concept is absorbed into something different altogether?
CONCLUSION FROM RESPONSES (see answer and comments below)
A hierarchy of exceptions makes sense if you want to recover from a non-leaf exception. Although, this doesn't prevent you from handling with Option/Try/Either
mechanisms which is more idiomatic than the traditional try/catch
.
First of all answering your question, the current implementation of exception hierarchy is the idiomatic way of declaring the hierarchy. This implementation is basically inherited from java style of coding. You map also refer to https://stackoverflow.com/a/10925402/7803797 for more details.
In my opinion, using such exceptions is a bad idea in Scala. Scala provides a beautiful construct called the Either type that allows you to handle exceptions gracefully. Please go through https://dzone.com/articles/catching-exceptions-in-scala-part-2
to understand this clearly.
Now explaining it in much more detail ...
Basically, in functional programming, composition is a key aspect. Now when you try to throw exceptions, you abruptly come out of the stack frame and the control of the code is delegated to the caller. Having a construct such as Left of type Either comes in handy here as it does not break composition. You are still in the same stack frame and exit from the method gracefully.
I hope this answers your question.