本文介绍了如何使用Google Guava的Throwables.propagateIfInstanceOf()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  try {
    someMethodThatCouldThrowAnything();
  } catch (IKnowWhatToDoWithThisException e) {
    handle(e);
  } catch (Throwable t) {
    Throwables.propagateIfInstanceOf(t, IOException.class);
    Throwables.propagateIfInstanceOf(t, SQLException.class);
    throw Throwables.propagate(t);
  }

不是很具体。真正的程序会是什么样子?我真的不明白方法的目的, propagate() propagateIfPossible()。我什么时候使用它们?

is not very concrete. How would a real program look like? I don't really understand the purpose of the methods Throwables.propagateIfInstanceOf(Throwable, Class), propagate(), propagateIfPossible(). When do I use them?

推荐答案

这些方法的目的是提供一种处理已检查异常的便捷方法。

The purpose of these methods is to provide a convenient way to deal with checked exceptions.

Throwables.propagate()是将已检查的异常包含在未经检查的异常中的常用习惯用法的简写(以避免声明它在方法的中抛出子句。)

Throwables.propagate() is a shorthand for the common idiom of retrowing checked exception wrapped into unchecked one (to avoid declaring it in method's throws clause).

Throwables.propagateIfInstanceOf()用于循环检查已检查的异常,如果它们的类型在方法的 throws 子句中声明。

Throwables.propagateIfInstanceOf() is used to retrow checked exceptions as is if their types are declared in throws clause of the method.

换句话说,有问题的代码

In other words, the code in question

public void doSomething() 
    throws IOException, SQLException {

    try {
        someMethodThatCouldThrowAnything();
    } catch (IKnowWhatToDoWithThisException e) {
        handle(e);
    } catch (Throwable t) {
        Throwables.propagateIfInstanceOf(t, IOException.class);
        Throwables.propagateIfInstanceOf(t, SQLException.class);
        throw Throwables.propagate(t);
    }  
}

是以下代码的简写:

public void doSomething() 
    throws IOException, SQLException {

    try {
        someMethodThatCouldThrowAnything();
    } catch (IKnowWhatToDoWithThisException e) {
        handle(e);
    } catch (SQLException ex) {
        throw ex;
    } catch (IOException ex) {
        throw ex;
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }  
}

另见:




  • Checked versus unchecked exceptions
  • The case against checked exceptions

这篇关于如何使用Google Guava的Throwables.propagateIfInstanceOf()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 06:13