Custom Exception in scala

前端 未结 7 860
你的背包
你的背包 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:29

    Similar to other answers, but I prefer to use a companion object instead of alternate constructors.

    class MyException(message: String, cause: Throwable = null) extends Exception(message, cause)
    
    object MyException {
      def apply(message: String): MyException = new MyException(message)
      def apply(message: String, cause: Throwable): MyException = new MyException(message, cause)
    }
    

提交回复
热议问题