J Smith
J Smith

Reputation: 2405

how to tell .NET not to terminate an application once it determines that an exception that is going to be thrown is not going to be caught?

There are some cases where control won't pass through the finally block of a try-catch-finally statement when the .NET framework determines that exceptions thrown by the catch block are not going to be caught anywhere in the code.

Can this behavior be configured, and if so how?

(Before you tell me that control ALWAYS passes through the finally block, feel free to conduct the following experiment and report your observations.)

  1. In VS, create a console application project
  2. Place a try-catch-finally statement inside the Main() method of the console application
  3. Write some code inside the finally block or a place breakpoint or anything that will allow you to tell whether control passed through the finally block.
  4. have the try block throw an exception
  5. have the catch block catch the exception
  6. have the catch block rethrow the exception
  7. If the version of VS/.NET installed on your machine behaves like mine does, control won't pass through the finally block.

Upvotes: 0

Views: 86

Answers (3)

J Smith
J Smith

Reputation: 2405

I think the observed behavior is related to the way the VS debugger was configured.

Upvotes: 0

T McKeown
T McKeown

Reputation: 12857

Works as expected when I rethrow the exception, code:

class Program
 {
    static void Main(string[] args)
    {
        System.Console.WriteLine("Start");
        try
        {
            System.Console.WriteLine("Try");
            throw new Exception("ttt");
        }
        catch (System.Exception ex)
        {
            System.Console.WriteLine("Catch");
            throw;
        }
        finally
        {
            System.Console.WriteLine("Finally");
        }
    }
}

here is my output from my code:

Start
Try
Catch

Unhandled Exception: System.Exception: ttt
at ConsoleApplication1.Program.Main(String[] args) in C:\Users\mckeownto01\Documents\Visual Studio    2010\Projects\MvcApplication1\ConsoleApplication1\Program.cs:line 21
Finally

Upvotes: 2

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112752

If you have a WinForms app, add these lines before Application.Run(new Form1()); in your Main routine.

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += Application_ThreadException;

And add this method to the Program class:

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
    //TODO: Handle the error here.
}

Upvotes: 0

Related Questions