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

后端 未结 10 2612
陌清茗
陌清茗 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:18

    You could do something like this:

    if (!IsReadOnly)
    {
        T newobj = null;
        try
        {
            newobj = DataPortal.Update<T>(this);    
        }
        catch (DataPortalException)
        {
            // TODO: Implement DataPortal.Update<T>() recovery mechanism
        }
        if (newobj != null)
        {
            List<string> keys = new List<string>(BasicProperties.Keys);
            foreach (string key in keys)
            {
                BasicProperties[key] = newobj.BasicProperties[key];
            }
        }
    }
    
    0 讨论(0)
  • 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
    0 讨论(0)
  • 2021-02-15 11:20

    Allow me to repeat an idea from a similar StackOverflow question. You cannot do this directly, but you can write a method that encapsulates the behavior you need. Look at the original question to see how to implement the method (if you're not familiar with lambda expressions and Func delegates). The usage could look like this:

    TryExceptRaise(() => { 
        // code that can throw exception
      }, (Exception e) => { 
        // code to run in case of an exception
        return (...); 
      }, () => {
        // code to run if there is no exception
        return (...);
      });
    
    0 讨论(0)
  • 2021-02-15 11:23

    Just put your "else" block before the catch. Then, it will only execute if code execution reaches that point:

    try
    {
        fee();
        fi();
        foe();
        fum();
    
        /// put your "else" stuff here. 
        /// It will only be executed if fee-fi-foe-fum did not fail.
    }
    catch(Exception e)
    {
        // handle exception
    }
    

    Given that, I fail to see the use of try..catch...else unless there's something vital missing from the OP's description.

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