C#: Equivalent of the python try/catch/else block

后端 未结 10 2643
陌清茗
陌清茗 2021-02-15 10:53

In Python, there is this useful exception handling code:

try:
    # Code that could raise an exception
except Exception:
    # Exception handling
else:
    # Cod         


        
10条回答
  •  心在旅途
    2021-02-15 11:19

    With C# version 7, you could use local functions to emulate this behaviour:

    Example 1: (since C# version 7)

    void Main()
    {
        void checkedCode()
        {
            try 
            {
                foo();
            }
            catch (Exception ex)
            {
                recover();
                return;
            }
            // ElseCode here
        }
        checkedCode();
    }
    

    If you prefer lambda syntax, you could also declare a run method

    void Run(Action r) { r(); }
    

    which only needs to be there once in your code, and then use the pattern for anonymous methods as follows

    Example 2: (older C# versions and C# version 7)

    Run(() => {
        try
        {
            foo();
        }
        catch (Exception)
        {
            recover();
            return;
        }
        // ElseCode here
    });
    

    whereever you need to enclose code in a safe context.

    Try it in DotNetFiddle


    Notes:

    • In both examples a function context is created so that we can use return; to exit on error.
    • You can find a similar pattern like the one used in Example 2 in JavaScript: Self-invoking anonymous functions (e.g. JQuery uses them). Because in C# you cannot self-invoke, the helper method Run is used.
    • Since Run does not have to be a local function, Example 2 works with older C# versions as well

提交回复
热议问题