1

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?

2
  • The main downside I can see is that since IOException is a checked exception, and since the method isn't handling it, the method header will have to have throws IOException. Commented Feb 24, 2014 at 22:54
  • The reason pointed was the use of IOException would clutter "the calling code considerably". I didn't understand that Commented Feb 24, 2014 at 23:01

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It goes quite a bit beyond recoverability, though.
1

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.

4 Comments

Probably it's also interesting to explain what the difference between Checked and Unchecked exception.
I know that. But author explain that even using a try-catch for a IOException is better rethrow that as RuntimeException. The reason pointed was the use of IOException would clutter "the calling code considerably". I didn't understand that.
@HellonCanellaMachado Declaring exceptions to be thrown and caught all over is noisy; it detracts from what the code is trying to actually do. Note that most other languages don't even have checked exceptions; some take that as evidence it was an experiment that failed. There are a lot of circumstances where the syntactic overhead of checked exceptions isn't worth it.
Thanks dude. I'll think of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.