Skip to content
Advertisement

Can I omit try-catch?

I want to fetch an HTML page and read in with BufferedReader. So I use try-with-resources to open it handles IOException this way:

try(BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) {
        
    } catch(IOException e) {
        throw e;
    }

Is this a good pattern to catch and instantly throw? And what if I omit try at all and state that function throws IOException? If then any potentional memory leak? Much appreciate any advice!

Advertisement

Answer

A catch block is not required in a try-with-resources statement. You could write the following, which would mean exactly the same as your original code:

try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(url.openStream()))) {
    // do something
}

So, you can leave out the catch block, if all you ever do there is immediately throw the same exception again.

You do want the try block however, so that the BufferedReader and underlying stream(s) are automatically closed at the end of the block.

Is this a good pattern to catch and instantly throw?

No, catching and immediately re-throwing the same exception does not add anything useful.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement