Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finally doesn't seem to execute in C# console application while using F5

int i=0;
try{
    int j = 10/i;
}
catch(IOException e){}
finally{
    Console.WriteLine("In finally");
    Console.ReadLine();
}

The finally block does not seem to execute when pressing F5 in VS2008. I am using this code in Console Application.

like image 812
Mohammad Nadeem Avatar asked Aug 06 '10 07:08

Mohammad Nadeem


2 Answers

The Visual Studio debugger halts execution when you get an uncaught exception (in this case a divide by zero exception). In debug mode Visual Studio prefers to break execution and give you a popup box at the source of the error rather than letting the application crash. This is to help you find uncaught errors and fix them. This won't happen if you detach the debugger.

Try running it in release mode from the console without the debugger attached and you will see your message.

like image 53
Mark Byers Avatar answered Oct 24 '22 11:10

Mark Byers


If you want it to execute while debugging there are two things you can do:

1) Catch the correct exception:


    int i = 0;
    try
    {
        int j = 10 / i;
    }
    catch(DivideByZeroException e){}
    finally
    {
        Console.WriteLine("In finally");
        Console.ReadLine();
    }

2) Tell Visual Studio to ignore unhandled exceptions. Go to Debug-->Exceptions, and then you can uncheck the Common Language Runtime Exceptions "User-unhandled" option, or you can expand that node, and uncheck individual exception types.

like image 30
JohnForDummies Avatar answered Oct 24 '22 10:10

JohnForDummies