Na página 359 do Livro: Java - Como Programar - 10ª Edição. Deitel explica o tratamento da exceções do Java. Ele exemplifica a questão com o seguinte código:
public class UsingExceptions {
public static void main(String[] args) {
try {
throwException();
}
catch (Exception exception) { // exception thrown by throwException
System.err.println("4 - Exception handled in main");
}
doesNotThrowException();
}
// demonstrate try...catch...finally
public static void throwException() throws Exception {
try { // throw an exception and immediately catch it
System.out.println("1 - Method throwException");
throw new Exception(); // generate exception
}
catch (Exception exception) { // catch exception thrown in try
System.err.println(
"2 - Exception handled in method throwException");
throw exception; // rethrow for further processing
// code here would not be reached; would cause compilation errors
}
finally { // executes regardless of what occurs in try...catch
System.err.println("3 - Finally executed in throwException");
}
// code here would not be reached; would cause compilation errors
}
// demonstrate finally when no exception occurs
public static void doesNotThrowException() {
try { // try block does not throw an exception
System.out.println("5 - Method doesNotThrowException");
}
catch (Exception exception) { // does not execute
System.err.println(exception);
}
finally { // executes regardless of what occurs in try...catch
System.err.println("6 - Finally executed in doesNotThrowException");
}
System.out.println("7 - End of method doesNotThrowException");
}
}
No livro, Deitel concorda comigo dizendo que a sequência lógica deste código é:
1 - Method throwException
2 - Exception handled in method throwException
3 - Finally executed in throwException
4 - Exception handled in main
5 - Method doesNotThrowException
6 - Finally executed in doesNotThrowException
7 - End of method doesNotThrowException
Porém, ao executar o código descrito no livro no Eclipse, o Java inverte a linha 6 com a 5 e o resultado fica assim:
1 - Method throwException
2 - Exception handled in method throwException
3 - Finally executed in throwException
4 - Exception handled in main
6 - Finally executed in doesNotThrowException
5 - Method doesNotThrowException
7 - End of method doesNotThrowException
Ou seja, o Java está chamando o bloco finally
do método doesNotThrowException
antes de entrar no método. Alguém sabe explicar o porquê?
stdout
estderr
. Você já tentou substituir as chamadas paraSystem.err
porSystem.out
?finally
ser executado antes do correspondente blocotry
é uma inversão de um comportamento bem estabelecido que não acontece no Java sob nenhuma hipótese. A execução dofinally
(que só em umas poucas situações muito peculiares deixa de acontecer, como no caso de ser precedida por umSystem.exit()
que finalize a JVM de imediato) é sempre, e por definição, posterior à conclusão normal (ou abreviada por lançamento de exceção) do blocotry
.