Catch multiple exceptions at once?

前端 未结 27 2309
夕颜
夕颜 2020-11-22 11:31

It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.

Now, this sometimes leads to unnecce

27条回答
  •  日久生厌
    2020-11-22 12:07

    If you can upgrade your application to C# 6 you are lucky. The new C# version has implemented Exception filters. So you can write this:

    catch (Exception ex) when (ex is FormatException || ex is OverflowException) {
        WebId = Guid.Empty;
    }
    

    Some people think this code is the same as

    catch (Exception ex) {                
        if (ex is FormatException || ex is OverflowException) {
            WebId = Guid.Empty;
        }
        throw;
    }
    

    But it´s not. Actually this is the only new feature in C# 6 that is not possible to emulate in prior versions. First, a re-throw means more overhead than skipping the catch. Second, it is not semantically equivalent. The new feature preserves the stack intact when you are debugging your code. Without this feature the crash dump is less useful or even useless.

    See a discussion about this on CodePlex. And an example showing the difference.

提交回复
热议问题