I find that the catch clause is never executed but the finally log is executed when my program exit.
That would mean that the try
block is NOT throwing an exception1.
The finally
block will be executed irrespective of how the try block and the chosen catch block (if any) terminates.
However, it could also be that your "finding" about the catch clause is incorrect.
Anyone could tell my how could this happen?
See above.
I am quite sure the code in try{} exit with some problem instead of normal exit.
On what evidence?
Since the code in try{} is doing a while loop and consume very much memory, so could the reason is that jvm exit because memory is used up?
That would result in an OutOfMemoryError
and the catch
block for Throwable
should catch that.
The only case where it is possible that the try
block throws an exception and the catch for Throwable
doesn't appear to work is if the catch
itself throws another exception ... before it does what you were trying to do (i.e. log the error). That scenario is possible if the first exception was OutOfMemoryError
. If the GC was unable to free any memory when the scope of the try
block exited, then a second OOME might be thrown if the logging code needed to create objects.
It should be noted that catching Throwable
is dangerous. It catches various Error
exceptions that should not be caught because they are not recoverable. Bad things can happen.
1 - It is also theoretically possible that Throwable
in your code is not java.lang.Throwable
, but only a crazy person would write and use their own Throwable
exception class .... and then forget that they had done that :-).