I'm trying to find the simplest yet proper way to extend a Java Exception
in Scala. For example, the following is not correct because new Exception(null, cause)
and new Exception(cause)
have different behavior according to Throwable.java
:
class InvalidVersionException(message: String = null, cause: Throwable = null)
extends IllegalArgumentException(message, cause) {
def this(message: String) = this(message, null)
// This is not same with super(cause)
def this(cause: Throwable) = this(null, cause)
}
Because I know Throwable(cause)
sets the message to cause.toString()
, I came up with the following:
class InvalidVersionException(message: String = null, cause: Throwable = null)
extends IllegalArgumentException(if ((message eq null) && (cause ne null)) cause.toString else message, cause) {
def this(message: String) = this(message, null)
def this(cause: Throwable) = this(null, cause)
}
However, this still has:
if ((message eq null) && (cause ne null)) cause.toString
which was duplicated from Throwable.java
.
Is there a better way to extend an Exception
without any code duplication?
It looks to me like you should be able to just change the cause-only constructor to:
def this(cause: Throwable) = this(cause.toString, cause)
EDIT: To handle null cause:
def this(cause: Throwable) = this(if (cause == null) "(no message)" else cause.toString, cause)
Replace "(no message)" with null (not recommended) or whatever text you feel is appropriate.
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