【问题标题】:Call Super Constructor调用超级构造函数
【发布时间】:2011-07-17 21:01:35
【问题描述】:

我有一个自定义异常类,如下所示:

case class CustomException(errorMsg:String)  extends Exception(error:String)

当我捕获异常时,我需要做的就是抛出我的自定义异常并将我的错误消息传递给自定义异常。 我希望从 CustomException 构造函数调用 super(errMsg) 但是,这不是现在的情况,我遇到了编译错误。

 catch {
      case s: Exception => throw CustomException("This is a custom message")
    }

如何调用超级构造函数:

super(errorMessage)

【问题讨论】:

    标签: scala


    【解决方案1】:
    case class CustomException(errorMsg:String)  extends Exception(errorMsg)
    

    【讨论】:

    • 谢谢。但是我很好奇为什么 Scala 没有像 Java 那样的 super(errorMsg) !!
    • @Echo:因为它不是 Java,并且因为超级构造函数只能从类的主构造函数中调用,即使这样 - 它也只能作为非常构造函数中的第一个操作。 Scala 的语法更好地代表了这个潜在的限制(由 JVM 强加)
    • 如果您希望在自定义异常中同时实现异常构造函数(字符串、可抛出)和(字符串)怎么办?
    • 好吧,我想出了一个解决方案:class FrontendException(message: String, t: Throwable) extends RuntimeException(message, t) { def this(m: String) = this(m, null); def this(t: Throwable) = this(null, t) } 但是当我在 scala 中使用空值时会有些伤害
    【解决方案2】:
    case class CustomException(errorMsg:String)  extends Exception(errorMsg)
    

    您正在调用超类的构造函数,但您传递的参数 (error) 没有绑定到任何东西。

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 1970-01-01
      • 2016-07-16
      • 2021-06-29
      • 2015-11-30
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多