From the docs Error Handling Docs: A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. Your exception never gets raised because you break before the try statement gets fully evaluated.
You can do that by catching the exception in the catch block of a try statement but leaving the body of the catch block empty. Here the FileNotFoundException is caught and ignored. This technique is called swallowing the exception.
A finally block always executes, regardless of whether an exception is thrown.
If the exception is not handled at the higher level, the application crashes. The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. Then the original exception that occurred in the try block is lost.
static int retIntExc() throws Exception{
int result = 1;
try {
result = 2;
throw new IOException("Exception rised.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
result = 3;
} finally {
return result;
}
}
A friend of mine is a .NET developer and currently migrating to Java and he ask me the following question about this source. In theory this must throw IOException("Exception rised.")
and the whole method retIntExc()
must throws Exception
. But nothing happens, the method returns 2.
I've not tested his example, but I think that this isn't the expected behavior.
EDIT: Thanks for all answers. Some of you have ignored the fact that method is called retIntExc
, which means that this is only some test/experimental example, showing problem in throwing/catching mechanics. I didn't need 'fix', I needed explanation why this happens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With