views:

905

answers:

10

Take this code:

using System;

namespace OddThrow
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                throw new Exception("Exception!");
            }
            finally
            {
                System.Threading.Thread.Sleep(2500);
                Console.Error.WriteLine("I'm dying!");
                System.Threading.Thread.Sleep(2500);
            }
        }
    }
}

Which gives me this output:

Unhandled Exception: System.Exception: Exception!
   at OddThrow.Program.Main(String[] args) in C:\Documents and Settings\username
\My Documents\Visual Studio 2008\Projects\OddThrow\OddThrow\Program.cs:line 14
I'm dying!

My question is: why does the unhandled exception text occur before the finally's? In my mind, the finally should be excuted as the stack unwinds, before we even know that this exception is unhandled. Note the calls to Sleep() - these occur after the unhandled exception is printed, as if it was doing this following:

  1. Unhandled exception text/message
  2. Finally blocks.
  3. Terminate application

According to the C# standard, §8.9.5, this behaviour is wrong:

  • In the current function member, each try statement that encloses the throw point is examined. For each statement S, starting with the innermost try statement and ending with the outermost try statement, the following steps are evaluated:
    • If the try block of S encloses the throw point and if S has one or more catch clauses, the catch clauses are examined in order of appearance to locate a suitable handler for the exception. The first catch clause that specifies the exception type or a base type of the exception type is considered a match. A general catch clause (§8.10) is considered a match for any exception type. If a matching catch clause is located, the exception propagation is completed by transferring control to the block of that catch clause.
    • Otherwise, if the try block or a catch block of S encloses the throw point and if S has a finally block, control is transferred to the finally block. If the finally block throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of the finally block, processing of the current exception is continued.
  • If an exception handler was not located in the current function member invocation, the function member invocation is terminated. The steps above are then repeated for the caller of the function member with a throw point corresponding to the statement from which the function member was invoked.
  • If the exception processing terminates all function member invocations in the current thread, indicating that the thread has no handler for the exception, then the thread is itself terminated. The impact of such termination is implementation-defined.

Where am I going wrong? (I've got some custom console error messages, and this is in-the-way. Minor, just annoying, and making me question the language...)

A: 

The try-catch-finally blocks are working exactly as you expected if they are caught at some point. When I wrote a test program for this, and I use various nesting levels, the only case that it behaved in a way that matched what you described was when the exception was completely unhandled by code, and it bubbled out to the operating system.

Each time I ran it, the OS was what created the error message. So the issue is not with C#, it is with the fact that an error that is unhandled by user code is no longer under the control of the application and therefore the runtime (I believe) cannot force an execution pattern on it.

If you had created a windows form application, and wrote all your messages to a textbox (then immediately flushing them) instead of writing directly to the console, you would not have seen that error message at all, because it was inserted into the error console by the calling application and not by your own code.

EDIT

I'll try to highlight the key part of that. Unhandled exceptions are out of your control, and you cannot determine when their exception handler will be executed. If you catch the exception at some point in your application, then the finally blocks will be executed before the lower-in-the-stack catch block.

Yes. We can all see that.
Malfist
The Sleep() call was to assure me that the finally() block was indeed occurring second, after whatever prints the "Unhandled exception message", and that I wasn't looking at some sort of I/O buffering/flushing on the console (although Error should be unbuffered). Take the Sleep()s out - the behaviour is the same.
Thanatos
+2  A: 

I could be way off base in the way I'm reading things...but you have a try finally block without a catch.

Juding by the description you posted, since the Exception is never caught, it bubbles up to the caller, works it's way up through the stack, is eventually unhandled, the call terminates, and then the finally block is called.

Justin Niessner
I do have a try/finally with no catch. This was by design.Read the segment of the standard that I posted - by my reading of it, finally() blocks should be executed as the stack is unwound, not after.
Thanatos
I'm reading it differently than you. It sounds to me like the exception will bubble up until it is handled (or it works its way up through the stack unhandled...which is happening in your case) and then the finally block will be executed.
Justin Niessner
@Thanatos, By that statement "finally() blocks should be executed as the stack is unwound, not after" you are showing that, in your example, 'handling' the unhandled exception occurs while the thread is sleeping.
strager
+2  A: 

The output is actually from the default CLR exception handler. Exception Handlers occur before the finally block. After the finally block the CLR terminates because of the unhandled exception (it can't terminate before, as c# guarantees [1] that the finally clause is called).

So I'd say it's just standard behaviour, exception handling occurs before finally.

[1] guranteed during normal operation at least in absence of internal runtime errors or power outage

Ben Schwehn
by "Exception Handlers occur before the finally block" - in a nested try, the inner try's finally is executed before the outer try's catch. I was expecting similiar behaviour here - and indeed, this is what the standard seems to say.
Thanatos
I agree, you're right. The standard doesn't even talk about the default unhandled exception handler at all. If you add an handler to AppDomain.CurrentDomain.UnhandledException this is executed before the finally as well
Ben Schwehn
A: 

A try/finally without a catch will use the default handler which does exactly what you see. I use it all the time, e.g., in cases where handling the exception would be covering an error but there's still some cleanup you want to do.

Also remember that output to standard error and standard out are buffered.

Arnshea
Error should be unbuffered - if it corresponsed to the std::cerr/stderr/file #2 of other languages. (What good would a buffered error be - your program would crash with the last error messages likely sitting in buffer)And a try/finally without a catch does not always exhibit this behaviour - only if the exception propagates all the way out of the program. catch-less trys are quite legal (and common).
Thanatos
Misses the point of the question. It's not about the "unhandled exception" message existing, it's about what order things happen in.
kdt
+1  A: 

Although not completely expected, the program does behave as it should. A finally block is not expected to be run first, it is only expected to be run always.

I adjusted your sample:

public static void Main()
{
    try
    {
     Console.WriteLine("Before throwing");
     throw new Exception("Exception!");
    }
    finally
    {
     Console.WriteLine("In finally");
     Console.ReadLine();
    }
}

In this case you will get the nasty unhandled exception dialog, but afterwards the console will output and wait for input, thus executing the finally, just not before windows itself catches the unhandled exception.

Dries Van Hansewijck
+2  A: 

I think this article may help you understand in more detail what is happening here.

http://bartdesmet.net/blogs/bart/archive/2006/04/04/clr-exception-handling-from-a-to-z-everything-you-didn-t-want-to-know-about-try-catch-finally-fault-filter.aspx

JD
The blog post is good but doesn't seem to mention the unhandled case at all nor how the microsoft clr than internally handles the exceptions at runtime.
Ben Schwehn
+2  A: 

To add more into the mix, consider this:

using System;
namespace OddThrow
{
    class Program
    {
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException +=
                delegate(object sender, UnhandledExceptionEventArgs e)
            {
                Console.Out.WriteLine("In AppDomain.UnhandledException");
            };
            try
            {
                throw new Exception("Exception!");
            }
            catch
            {
                Console.Error.WriteLine("In catch");
                throw;
            }
            finally
            {
                Console.Error.WriteLine("In finally");
            }
        }
    }
}

Which on my system (Norwegian) shows this:

[C:\..] ConsoleApplication5.exe
In catch
In AppDomain.UnhandledException

Ubehandlet unntak: System.Exception: Exception!
   ved OddThrow.Program.Main() i ..\Program.cs:linje 24
In finally
Lasse V. Karlsen
+5  A: 

The standard's statements about the order of execution are correct, and not inconsistent with what you are observing. The "Unhandled exception" message is allowed to appear at any point in the process, because it is just a message from the CLR, not actually an exception handler itself. The rules about order of execution only apply to code being executed inside the CLR, not to what the CLR itself does.

What you've actually done is expose an implementation detail, which is that unhandled exceptions are recognised by looking at a stack of which try{} blocks we are inside, rather than by actually exploring all the way to the root. Exceptions may or may not be handled by looking at this stack, but unhandled exceptions are recognised this way.

As you may be aware, if you put a top-level try{}catch{} in your main function, then you will see the behaviour you expect: each function's finally will be executed before checking the next frame up for a matching catch{}.

kdt
You're correct about the top-level try/catch - I was just hoping to not have to. Seems I'm not so lucky. I think I'll just have to work around this.I agree though - this seems to be a CLR message, perhaps for helpful purposes, that does not qualify as an exception handler.
Thanatos
Yes- I'm thinking that those closing words "implementation-defined" are key here, and is what I'm looking at.
Thanatos
A: 

To put a couple of answers together, what happens is that as soon as you have a Unhandled Exception a UnhandledExceptionEvent is raised on the AppDomain, then the code continues to execute (i.e. the finally). This is the MSDN Article on the event

Andrew Cox
A: 

Next try:

  1. I believe this case isn't mentioned in the c# standard and I agree it seems to almost contradict it.

  2. I believe the internal reason why this is happening is somewhat like this: The CLR registers its default exception handler as SEH handler into FS:[0] when you have more catches in your code, those handlers are added to the SEH chain. Alternatively, only the CLR handler is called during SEH handling and handles the CLR exception chain internally, I don't know which.

In your code when the exception is thrown, only the default handler is in the SEH chain. This handler is called before any stack unrolling begins.

The default exception handler knows that there are no exception handler registered on the stack. Therefore it calls all registered UnhandledException handler first, then prints its error message and marks the AppDomain for unloading.

Only after that stack unrolling even begins and finally blocks are called according the c# standard.

As i see it, the way the CLR handles unhandled exception isn't considered in the c# standard, only the order in which finallys are called during stack unrolling. This order is preserved. After that the "The impact of such termination is implementation-defined." clause takes effect.

Ben Schwehn