简体   繁体   English

为什么抛出RuntimeException错误而不是IOException消息?

[英]Why throw RuntimeException Error instead of IOException Message?

I get this piece of code from a game book. 我从游戏书中获得了这段代码。 The author explains that it will open a music file 作者解释它将打开一个音乐文件。

public Music newMusic(String filename) {
    try {
        AssetFileDescriptor assetDescriptor = assets.openFd(filename);
        return new AndroidMusic(assetDescriptor);
    } catch (IOException e) {
        throw new RuntimeException("Couldn't load music '" + filename + "'");
    }
}

The method AssetFileDescriptor.openFd(filename) throws a IOException . 方法AssetFileDescriptor.openFd(filename) throws a IOException

My question is: why do we need throw a RuntimeException message instead of IOException message? 我的问题是:为什么我们需要抛出RuntimeException消息而不是IOException消息?

An IOException is a checked exception and must be declared by any method that throws it. IOException是已检查的异常,并且必须由引发该异常的任何方法声明。 A RuntimeException is unchecked and can be thown from any method. RuntimeException未被选中,可以从任何方法中抛出。

Wrapping a checked exception in a RuntimeException, as in the example code, is normally done when the checked exception cannot be recovered from locally and it's considered acceptable for the exception to result in the program's failure. 如示例代码中所示,通常在无法从本地恢复检查的异常并且认为异常导致程序失败的情况下,可以在RuntimeException中包装检查的异常。 Once the checked exception is wrapped in the RuntimeException, the RuntimeException can then propagate all the way up the stack, if it occurs, regardless of the presence or absence of exception declarations. 一旦将检查的异常包装在RuntimeException中,然后RuntimeException便可以一直传播到整个堆栈(如果发生),而不管是否存在异常声明。

So you don't need to declare the calling methods as catching or throwing IOException . 因此,您无需将调用方法声明为catch或throwing IOException

Checked exceptions may be nice in some situations, but not everywhere. 在某些情况下,但并非在所有情况下,检查异常都可能很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM