问题
Code:
catch (IOException e) {
LOGGER.error("IOException exception happened");
//now need throw again the same exception to be
//catched in the upper method
}
But when I try simply:
catch (IOException e) {
LOGGER.error("IOException exception happened");
//now need throw again the same exception to be
//catched in the upper method
throw e;
}
Eclipse supposes to me put "throw e" in try catch block. But this is nonsense. How fix this problem? Thanks.
回答1:
Since IOException is a checked exception, that method needs to be declared as throwing IOException
if you want it to propagate. For example:
void myMethod() throws IOException {
try {
//code
}
catch(IOException e) {
LOGGER.error("IOException exception happened");
throw e;
}
}
回答2:
The second code fragment is just fine. Just remember that You have to declare Your method as:
public void myMethod() throws IOException {
...
}
回答3:
Try adding throws IOException
to your method, e.g.:
private void yourMethodName() throws IOException {
# your method
}
Then Eclipse won't ask for the second try catch block.
来源:https://stackoverflow.com/questions/11209885/how-to-throw-again-ioexception-in-java