Trying to understand exceptions in C#

前端 未结 7 1731
日久生厌
日久生厌 2020-12-11 21:18

I do not really use any try/catches in my code ever but I\'m trying to break that habit and now get in to using exceptions.

I figure the most important place to have

相关标签:
7条回答
  • 2020-12-11 22:06

    In your code you are triggering the xxx when you evaluate the condition inside the if statement.

    Asking person["Name"] == null || person["Job"] == null || person["HairColor"] == null will fail if any of those keys are not in your dictionary.

    You need to do this instead:

    if (!person.ContainsKey("Name"] ||
        !person.ContainsKey("Job"] ||
        !person.ContainsKey("HairColor"))
    

    So, your call to throw the exception is never executed! And that's why you never see your message.

    I would keep your habit of not doing exceptions for this kind of coding. Exceptions are expensive and can cause real issues in your code to be hidden.

    Don't catch general exceptions and don't create exceptions for non-exceptional circumstances.

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