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

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

    I would prefer to see the rest of the code outside the try/catch so it is clear where the exception you are trying to catch is coming from and that you don't accidentally catch an exception that you weren't trying to catch.

    I think the closest equivalent to the Python try/catch/else is to use a local boolean variable to remember whether or not an exception was thrown.

    bool success;
    
    try
    {
        foo();
        success = true;
    }
    catch (MyException)
    {
        recover();
        success = false;
    }
    
    if (success)
    {
        bar();
    }
    

    But if you are doing this, I'd ask why you don't either fully recover from the exception so that you can continue as if there had been success, or else fully abort by returning an error code or even just letting the exception propagate to the caller.

提交回复
热议问题