Por que o java não detecta blocos de captura inacessíveis se eu uso vários blocos de captura?
Pesquise o seguinte método:
static private void foo() {
try {
throw new FileNotFoundException();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Esse código compila bem, apesar do último bloco de captura realmente inacessível.
Agora vamos comentarthrow new FileNotFoundException();
linha
executar:
OOOPs! Nós vemos
Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body
Estranho. Por que o java usa padrões duplos para essas situações?
atualização para @Peter Raderstatic private void foo(FileNotFoundException f) {
try {
throw f;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
trabalhar, bem como com a chamada de construtor
atualizarNotei que em versões diferentes do compilador java vejo resultados diferentes da compilação desse código.
public class RethowTest {
public static void main(String[] args) {
try {
throw new FileNotFoundException();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
throw e;
}
}
}
no meu PC local: java 1.7.0_45 -
C:\Program Files\Java\jdk1.7.0_45\bin>javac D:\DNN-Project\DNN-Project\src\main\java\exceptionsAndAssertions\RethowTest.java
D:\DNN-Project\DNN-Project\src\main\java\exceptionsAndAssertions\RethowTest.java:15: warning: unreachable catch clause
} catch (IOException e) {
^
thrown type FileNotFoundException has already been caught
1 warning
java 1.6.0_38
D:\DNN-Project\DNN-Project\src\main\java\exceptionsAndAssertions\RethowTest.java:16: unreported exception java.io.IOException; must be caught or declared to be thrown
throw e;
^
1 error
http://www.compileonline.com/compile_java_online.php (Javac 1.7.0_09) -
HelloWorld.java:9: warning: unreachable catch clause
} catch (IOException e) {
^
thrown type FileNotFoundException has already been caught
1 warning