Tuesday, 20 August 2013

What is the best way to extend a Java Exception in Scala properly?

What is the best way to extend a Java Exception in Scala properly?

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?

No comments:

Post a Comment