0

Can anyone give me a reason why new Exception() is ignored here?

void bar() throws IOException { //no Exception declared, compilator is ok about that. Why?
 try{
   throw new EOFException();
 }
 catch(EOFException eofe){
   throw new Exception();
 }
 finally{
    throw new IOException();
 }
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 1
    Because there is no way for the function to throw `EOFException` or `Exception`, as `IOException` will always preempt them. – Amadan Oct 17 '18 at 10:39
  • Yes but why compilator doesn't complain about we haven't added `throws Exception` in method declaration? – Mukhamedali Zhadigerov Oct 17 '18 at 10:59
  • @Oleksandr If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten). ??? – Mukhamedali Zhadigerov Oct 17 '18 at 11:00

1 Answers1

5

The finally block is always executed, regardless of whether the try block throws an exception or not (and regardless of whether it has a return statement or not).

Therefore, the exception thrown by the finally block - IOException - is the only exception thrown by your method, and it's always thrown, regardless of the content of the try block. Therefore your method only has to declare that it throws IOException.

Eran
  • 387,369
  • 54
  • 702
  • 768