Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the correct rethrow code look like for this example

Tags:

java

exception

Yesterday I red this article about the new Exception Handling in Java 7.

In the article they show an example (No 4) which is not working in Java 6. I just copied it.

public class ExampleExceptionRethrowInvalid {

public static void demoRethrow()throws IOException {
    try {

        // forcing an IOException here as an example,
        // normally some code could trigger this.
        throw new IOException("Error");
    }
    catch(Exception exception) {
        /*
         * Do some handling and then rethrow.
         */
        throw exception;
    }
}

public static void main( String[] args )
{
    try {
        demoRethrow();
    }
    catch(IOException exception) {
        System.err.println(exception.getMessage());
    }
}
}

Like in the article descriped it won't compile, because of the type missmatch -throws IOException- and -throw exception-. In Java 7 it will. So my question is.

How do I proper implement this kind of rethrowing of an exception in Java 6? I don't like the suggested implementation example no five. I know it is a matter of taste and problem you try to handle if unchecked exceptions or not. So what can I do to get the -throws IOException- and keep the stack trace? Should I only change the catch to IOException and risk not catching all?

I'm curious about your answers.

like image 835
Christian Avatar asked Mar 23 '26 08:03

Christian


2 Answers

Simply catch IOException, like so:

public static void demoRethrow()throws IOException {
    try {
        // forcing an IOException here as an example,
        // normally some code could trigger this.
        throw new IOException("Error");
    }
    catch(IOException exception) {
        /*
         * Do some handling and then rethrow.
         */
        throw exception;
    }
}

If the code inside the try block can throw a checked exception other than IOException, the compiler will flag this up as an error, so you're not "risk[ing] not catching all".

If you're also interested in unchecked exceptions, you could also catch and re-throw RuntimeException (you won't need to declare it in the throws clause).

like image 134
NPE Avatar answered Mar 25 '26 22:03

NPE


Catch IOException and everything else separately:

public static void demoRethrow() throws IOException {
    try {
        throw new IOException("Error");
    }
    catch(IOException exception) {
        throw exception;
    }
    catch(Exception exception) {
        throw new IOException(exception);
}
like image 27
Tomasz Nurkiewicz Avatar answered Mar 25 '26 20:03

Tomasz Nurkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!