Custom Exception in scala

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

    In order to reflect all the original constructors from Exception I'd implement a custom exception with the following pattern:

    class CustomException(msg: String) extends Exception(msg) {
      def this(msg: String, cause: Throwable) = {
        this(msg)
        initCause(cause)
      }
    
      def this(cause: Throwable) = {
        this(Option(cause).map(_.toString).orNull)
        initCause(cause)
      }
    
      def this() = {
        this(null: String)
      }
    }
    

    This can be also achieved with a trait as mentioned in previous answer. I'd just not create individual classes in this case:

    trait SomeException { self: Throwable =>
      def someDetail: SomeDetail
    }
    

    then, when throwing:

    throw new Exception(...) with SomeException {
      override val someDetail = ...
    }
    

    and when matching:

    try {
      ...
    } catch {
      case ex: Throwable with SomeException =>
        ex.getCause
        ex.getMessage
        ex.someDetail
    }
    

    The advantage here is that you are not sticking to any particular constructor of the parent exception.

    something more or less like that.

提交回复
热议问题