-
C#: "finally" block vs StackOverflowException
-
Posted @ Aug 26, 2008 06:59 PM | Permalink
-
Taken from the MSDN documentation:
The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception.
So in other words whatever code you have in your "finally" block will always execute when an exception occurs, right? Wrong. The correct answer is - it depends on the error.
Let me give you a simple example:
1
2 static void Main(string[] args) {
3 try {
4 Console.WriteLine("Try block");
5
6 Recurse();
7 }
8 catch {
9 Console.WriteLine("Catch block");
10 }
11 finally {
12 Console.WriteLine("Finally block");
13
14 Console.ReadLine();
15 }
16 }
17
18 static void Recurse() {
19 Recurse();
20 }
21
The System.StackOverflowException is an exception that will NOT execute codes in your catch and finally blocks.
Hope this helps.
-
Tags: C#, Error Handling
- I didn't believe you until I looked up StackOverflowException on MSDN. That's pretty interesting and will make for some great trivia at a code camp sometime. From MSDN: "Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default."
- I've been interviewing applicants this week and this was one of my "trick" questions. They all answered me, with confidence, saying that the finally block will always execute regardless of the kind of exception.
I guess not a lot of people know about this.
- Out of curiosity, I asked some senior level .net developers on my project about this. Some suspected there was a case that the finally block wouldn't execute, others stated confidently that it will always execute. No one knew which exception caused it to not execute.
It's not something you come across very often. About the worse I can imagine happening because of this is unmanaged resources being left open. Unit testing would catch this before it caused damages in a production environment. If one utilizes good practices, it's not something to be too concerned about.
- This exception is common in recursive routines or infinite loops and will be of concern if one doesn't test his work.
Leave a Comment