Reputation: 456
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
.
My question is: why do we need throw a RuntimeException
message instead of IOException
message?
Upvotes: 1
Views: 2598
Reputation: 8928
An IOException is a checked exception and must be declared by any method that throws it. A RuntimeException is unchecked and can be thown from any method.
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. 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.
Upvotes: 4
Reputation: 160191
So you don't need to declare the calling methods as catching or throwing IOException
.
Checked exceptions may be nice in some situations, but not everywhere.
Upvotes: 1