Why use Finally in Try … Catch

前端 未结 14 1973
鱼传尺愫
鱼传尺愫 2020-12-05 06:38

I see that the Finally in Try .. Catch will always execute after any parts of the execution of the try catch block.

Is it any different to

相关标签:
14条回答
  • 2020-12-05 07:05

    Yes, it is different. Finally will always run (barring program crash). If the function exits inside of the try catch block, or another error is thrown in either the try or the catch, the finally will still execute. You won't get that functionality not using the finally statement.

    0 讨论(0)
  • 2020-12-05 07:06

    What I often use is (I encapsulated that into an aspect, but this is what I derived the aspect of):

    public static DoLengthyProcessing(this Control control, Action<Control> action)
    {
        Cursor oldCursor = control.Cursor
        try
        {
            control.Cursor = Cursors.WaitCursor;
            action(control);
        }
        catch (Exception ex)
        {
            ErrorHandler.Current.Handler(ex);
        }
        finally
        {
            control.Cursor = oldCursor;
        }
    }
    

    Or, use AOP (as I do).

    0 讨论(0)
提交回复
热议问题