Custom Exception in scala

前端 未结 7 834
你的背包
你的背包 2020-12-24 12:02

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 :

相关标签:
7条回答
  • 2020-12-24 12:50
    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 nulls, 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?

    • Perfectly maintaining the constructors' behavior regarding nulls 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.
    • The message and the cause are already publicly available via getMessage and getCause. Adding another reference to these is redundant.
    • equals will be overridden and will behave differently.
      Meaning, new Exception("m") == new Exception("m") // false
      while 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))
    }
    
    0 讨论(0)
提交回复
热议问题