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

后端 未结 10 2646
陌清茗
陌清茗 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: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 (...);
      });
    

提交回复
热议问题