Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 257
trustin Avatar asked Nov 01 '22 16:11

trustin


1 Answers

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.

like image 64
Shadowlands Avatar answered Nov 15 '22 06:11

Shadowlands