Scala:如何捕获父类的构造函数抛出的异常?

时间:2016-03-08 20:07:15

标签: scala

说我有以下内容:

class Parent {
  // does some things that may result in an exception
  throw new IllegalArgumentException
}

class Child extends Parent

我希望Child的构造函数能够捕获,包装和重新抛出Parent构造函数抛出的异常。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

不幸的是,它似乎无法完全按照您的意愿行事。 Parent Child构造函数的调用仅由extends声明的Child部分控制,辅助Child构造函数可以调用Parent }}构造函数只能通过主Child构造函数(参见this Scala Cookbook entry

但是,作为替代方法,您可以将Child构造函数设为私有,而是通过包装抛出的任何异常的工厂方法实例化Child

class Child private extends Parent

object Child {
  def apply() = {
    try {
      new Child
    } catch {
      case e: IllegalArgumentException => throw new WrappedException(e)
    }
  }
}

val foo = Child() // throws WrappedException

请注意,这也将捕获,包装和重新抛出Child本身的构造函数抛出的任何IllegalArgumentException

答案 1 :(得分:0)

这不是你要求的:

scala> class Parent(i: Int) { if (i > 40) throw new IllegalArgumentException }
defined class Parent

scala> new Parent(0)
res0: Parent = Parent@3e74829

scala> new Parent(42)
java.lang.IllegalArgumentException
  ... 29 elided

scala> class Child extends Parent({ try new Parent(42) catch { case _: IllegalArgumentException => throw new RuntimeException }; 42})
defined class Child

scala> new Child
java.lang.RuntimeException
  at Child.liftedTree1$1(<console>:12)
  ... 29 elided

但它建议

scala> class Parent(val i: Int) { def this(p: Parent) = this(p.i) ; if (i > 40) throw new IllegalArgumentException }
defined class Parent

scala> class Child extends Parent({ val p = try new Parent(42) catch { case _: IllegalArgumentException => throw new RuntimeException }; p})
defined class Child

scala> new Child
java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    Child.<init>()V @2: invokespecial
  Reason:
    Type uninitializedThis (current frame, stack[1]) is not assignable to 'Child'
  Current Frame:
    bci: @2
    flags: { flagThisUninit }
    locals: { uninitializedThis }
    stack: { uninitializedThis, uninitializedThis }
  Bytecode:
    0x0000000: 2a2a b700 254c 2bb7 0028 b1

  ... 28 elided

好的,没关系。