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-.开发者_Go百科 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.
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).
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);
}
catch(Exception ex) catches both checked and unchecked (RuntimeException) exceptions. So to make it functionaly equivalent,
public static void demoRethrow() throws IOException {
try {
throw new IOException("Error");
}
catch(IOException exception) {
throw exception;
}
catch(RuntimeException exception) {
throw new IOException(exception);
}
suffice, and compiler will detect other checked exceptions (good for thinking again about whether they should realy get this far, or should have bean delt with before)
A hacky way to throw to catch a generic exception and rethrow without the compiler checking the exception is to use stop.
public static void demoRethrow() throws IOException {
try {
throw new IOException("Error");
} catch(Throwable t) {
// handle exception
// rethrow the exception without compiler checks.
Thread.currentThread().stop(t);
}
}
精彩评论