我们在Scala中抑制了异常吗?

时间:2019-05-09 17:09:09

标签: scala exception try-with-resources

在Scala中,我们可以在finally块中添加异常引发作为受抑制的异常返回到原始异常吗?

在Java中,如果我们在try块中遇到一个异常,然后在finally块中遇到另一个异常,则第二个异常将作为抑制的异常添加回第一个异常。因此,第二个异常不会掩盖第一个异常,我们仍然可以通过检查其抑制的异常来分析发生的情况。

import java.util.stream.Stream;

class Scratch {
    static class MyCloseable implements AutoCloseable {
        @Override
        public void close() throws Exception {
            throw new Exception("FROM CLOSE METHOD");
        }
    }

    public static void main(String[] args) {

        try {
            try (final MyCloseable closeable = new MyCloseable()){
                throw new Exception("From Try Block");
            }
        } catch (Throwable t) {
            System.out.println(t);
            Stream.of(t.getSuppressed()).forEach(System.out::println);
        }
    }
}

会抛出异常

  • java.lang.Exception: From Try Block
  • java.lang.Exception: FROM CLOSE METHOD

但是,似乎Scala只是简单地重新抛出了第二个异常(从finally块抛出)而忽略了第一个异常(从try块抛出)。

try {
  try {
    throw new Exception("From Try Block")
  } finally {
    throw new Exception("From Final Block")
  }
} catch {
  case e => e :: e.getSuppressed().toList
}

上面的代码将只返回第二个异常(从final块抛出)。但是,我希望有一种方法可以同时获得这两个异常。

是否有更好的方法制作上述代码?

1 个答案:

答案 0 :(得分:3)

由于Scala不支持Java的try-with-resources构造,因此我认为有一种明显的方法可以使上面的代码更好地存储=第一个异常:

    try {
      var te: Option[Throwable] = None
      try {
        throw new Exception("From Try Block")
      } catch {
        case t: Throwable =>
          te = Some(t)
          throw t
      } finally {
        try {
          throw new Exception("From Final Block")
        } catch {
          case fe: Throwable =>
            throw te.map { e => e.addSuppressed(fe); e }.getOrElse(fe)
        }
      }
    } catch {
      case e: Throwable =>
        (e :: e.getSuppressed().toList).foreach(println)
    }

输出:

java.lang.Exception: From Try Block
java.lang.Exception: From Final Block

下面是在实际项目中使用的更好的方法:

  def withResources[T <: AutoCloseable, V](r: => T)(f: T => V): V = {
    val resource: T = r
    var e: Option[Throwable] = None

    try f(resource)
    catch {
      case t: Throwable =>
        e = Some(t)
        throw t
    } finally e.fold(resource.close())(te =>
      try resource.close()
      catch {
        case t: Throwable =>
          te.addSuppressed(t)
          throw te
      })
  }
    val resource = new AutoCloseable {
      override def close(): Unit = throw new Exception("From Final Block")
    }

    try {
      withResources(resource)(_ => throw new Exception("From Try Block"))
    } catch {
      case e: Throwable =>
        (e :: e.getSuppressed().toList).foreach(println)
    }

输出:

java.lang.Exception: From Try Block
java.lang.Exception: From Final Block