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 :
class CustomException extends Exception { public final static String _FAIL_TO_INSERT = "FAIL_TO_INSERT"; }
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.
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. Exception handling in java and scala are very similar.
However, unlike Java, Scala has no “checked” exceptions—you never have to declare that a function or method might throw an exception. In Java, “checked” exceptions are checked at compile time. If your method might throw an IOException, you must declare it.
final case class CustomException(private val message: String = "", private val cause: Throwable = None.orNull) extends Exception(message, cause)
Just try catch:
try { throw CustomException("optional") } catch { case c: CustomException => c.printStackTrace }
class MyException(message: String) extends Exception(message) { def this(message: String, cause: Throwable) { this(message) initCause(cause) } def this(cause: Throwable) { this(Option(cause).map(_.toString).orNull, cause) } def this() { this(null: String) } }
This is almost identical to @Jacek L.'s answer. I just wanted to add some more input on the motive behind this answer.
Why so many constructors?
Throwable
is written in kind of a funny way. It has 4 constructors -- ignoring the one with the boolean
toggles -- each of them behaves a bit differently with null
s, and these differences could only be maintained with multiple constructors.
It would have been a bit cleaner if Scala would have allowed to call a superclass constructor via super
, but it doesn't :(
Why not a case class?
null
s wouldn't be possible; specifically, both def this()
and def this(message: String)
will have to set the cause
to null
, while originally it is set to this
.toString
will not be overridden.getMessage
and getCause
. Adding another reference to these is redundant.equals
will be overridden and will behave differently.new Exception("m") == new Exception("m") // false
new CaseException("m") == new CaseException("m") // true
If one desires to access the message and the cause via pattern-matching, one can simply implement the unapply
method:
object MyException { def unapply(e: MyException): Option[(String,Throwable)] = Some((e.getMessage, e.getCause)) }
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