C# try-catch-else

后端 未结 14 1524
暗喜
暗喜 2020-12-30 19:44

One thing that has bugged me with exception handling coming from Python to C# is that in C# there doesn\'t appear to be any way of specifying an else clause. For example, in

14条回答
  •  滥情空心
    2020-12-30 20:35

    If you happen to be in a loop, then you can put a continue statement in the catch blocks. This will cause the remaining code of that block to be skipped.

    If you are not in a loop, then there is no need to catch the exception at this level. Let it propagate up the call stack to a catch block that knows what to do with it. You do this by eliminating the entire try/catch framework at the current level.

    I like try/except/else in Python too, and maybe they will get added to C# some day (just like multiple return values were). But if you think about exceptions a little differently, else blocks are not strictly necessary.

提交回复
热议问题