In java exceptions have at least these four constructors:
Exception() Exception(String message) Exception(String message, Throwable cause) Exception(Throwable cause)
If you want to define your own extensions, you just have to declare a descendent exceptions and implement each desired constructor calling the corresponden super constructor
How can you achieve the same thing in scala?
so far now I saw this article and this SO answer, but I suspect there must be an easier way to achieve such a common thing
An exception is an event that changes the normal flow of a program. Exception handling is the mechanism to respond to the occurrence of an exception. Exceptions can be checked or unchecked. Scala only allows unchecked exceptions, though.
Like Java, Scala has a try/catch/finally construct to let you catch and manage exceptions. The main difference is that for consistency, Scala uses the same syntax that match expressions use: case statements to match the different possible exceptions that can occur.
The throw keyword in Scala is used to explicitly throw an exception from a method or any block of code.In scala, throw keyword is used to throw exception explicitly and catch it. It can also be used to throw custom exceptions.
Default value for cause
is null. And for message
it is either cause.toString()
or null:
val e1 = new RuntimeException() e.getCause // res1: java.lang.Throwable = null e.getMessage //res2: java.lang.String = null val cause = new RuntimeException("cause msg") val e2 = new RuntimeException(cause) e.getMessage() //res3: String = java.lang.RuntimeException: cause msg
So you can just use default values:
class MyException(message: String = null, cause: Throwable = null) extends RuntimeException(MyException.defaultMessage(message, cause), cause) object MyException { def defaultMessage(message: String, cause: Throwable) = if (message != null) message else if (cause != null) cause.toString() else null } // usage: new MyException(cause = myCause) // res0: MyException = MyException: java.lang.RuntimeException: myCause msg
well, this is the best I've found so far
class MissingConfigurationException private(ex: RuntimeException) extends RuntimeException(ex) { def this(message:String) = this(new RuntimeException(message)) def this(message:String, throwable: Throwable) = this(new RuntimeException(message, throwable)) } object MissingConfigurationException { def apply(message:String) = new MissingConfigurationException(message) def apply(message:String, throwable: Throwable) = new MissingConfigurationException(message, throwable) }
this way you may use the "new MissingConfigurationException" or the apply method from the companion object
Anyway, I'm still surprised that there isn't a simpler way to achieve it
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