finally doesn't seem to execute in C# console

2019-06-15 14:55发布

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.

5条回答
Melony?
2楼-- · 2019-06-15 15:12

Don't run you application via F5. In Debug mode you can't skip exception, message box will pop-up again and again.

Instead build it and run via CMD, Far Manager, etc

查看更多
老娘就宠你
3楼-- · 2019-06-15 15:15

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.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-06-15 15:28

As the final conclusion we all should agree, if there is an unhandled exception and the application is running in Debugging mode, finally won't get executed.

查看更多
ら.Afraid
5楼-- · 2019-06-15 15:33

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.

查看更多
Rolldiameter
6楼-- · 2019-06-15 15:34

F5 continues the application till the next breakpoint or unhandled exception.

I think you should use F10 rather for step debugging or turn on breaking for all exceptions (handled or not).

查看更多
登录 后发表回答