I have some critical logic in a finally block (with an empty try block), because I want to guarantee that the code gets executed even if the thread is aborted. However, I’d also like to detect the ThreadAbortException. I’ve found that wrapping my critical try/finally block in a try/catch does not catch the ThreadAbortException. Is there any way to detect it?
try {
try { }
finally {
// critical logic
}
} catch(Exception ex) {
// ThreadAbortException is not caught here, but exceptions thrown
// from within the critical logic are
}
This is a curious problem.
The code you posted should work. It seems there’s some kind of optimization going on that decides not to call your catch handler.
So, I wanted to detect the exception with this:
(My actual code just slept in that critical code section, so I could be sure it would abort after that finally.)
It printed:
Hmmm, strange indeed!
So I thought about doing a little bit more work there, to trick any “smart” optimizations:
Where
AmIEvilis just:Finally it printed:
And there you have it. Use this in your code:
Where
NoOpis just: