2016-11-18 149 views
0

在此代码中,是否需要throw关键字才能传播异常?是否有必要使用Throwables.propagate(e)使用throw关键字?

try { 
    //try something 
} catch (Exception e) { 
    throw Throwables.propagate(e); 
} 

Throwables文档中说,此方法始终抛出一个异常 - 被添加throw多余的?我能否写下以下内容?

try { 
    //try something 
} catch (Exception e) { 
    Throwables.propagate(e); 
} 

回答

4

javadoc还指出

RuntimeException返回类型仅适用于客户端代码使Java 类型系统的情况下,幸福的返回值被包围 方法所需。

,然后提供这个例子

T doSomething() { 
    try { 
    return someMethodThatCouldThrowAnything(); 
    } catch (IKnowWhatToDoWithThisException e) { 
    return handle(e); 
    } catch (Throwable t) { 
    throw Throwables.propagate(t); 
    } 
} 

换句话说,返回类型(RuntimeException)是必要的,这样就可以在returnthrows语句使用的方法。

在上面的例子,如果你在过去catch块省略throw,那么Java编译器会因为它不能保证该值会从catch块返回报告错误。 A return or throws instead indicate that the method completes at that point, abruptly.

+0

我得到了什么问题?为什么downvote? –

相关问题