how can i create custom exceptions in Scala extending Exception
class and throw them when exception occurs as well as catch them.
example in java :
In order to reflect all the original constructors from Exception I'd implement a custom exception with the following pattern:
class CustomException(msg: String) extends Exception(msg) {
def this(msg: String, cause: Throwable) = {
this(msg)
initCause(cause)
}
def this(cause: Throwable) = {
this(Option(cause).map(_.toString).orNull)
initCause(cause)
}
def this() = {
this(null: String)
}
}
This can be also achieved with a trait as mentioned in previous answer. I'd just not create individual classes in this case:
trait SomeException { self: Throwable =>
def someDetail: SomeDetail
}
then, when throwing:
throw new Exception(...) with SomeException {
override val someDetail = ...
}
and when matching:
try {
...
} catch {
case ex: Throwable with SomeException =>
ex.getCause
ex.getMessage
ex.someDetail
}
The advantage here is that you are not sticking to any particular constructor of the parent exception.
something more or less like that.