Exceptions: When to use, timing, overall use

后端 未结 6 1537
-上瘾入骨i
-上瘾入骨i 2020-12-20 07:47

I\'ll try and ask my question so it doesn\'t end as a simple argumentative thread.

I\'ve jumped into an application coded in C# recently and I\'m discovering the exc

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 08:30

    Ahh, if only it was that simple! But, alas - the decision when to use exceptions is more often subjective than not. Still, there are guidelines you can use. For example, Microsoft has some.

    All in all, the rule of thumb for throwing exceptions is - you only throw an exception when a function cannot do what it was supposed to do. Basically each function has a contract - it has a legal range of input values and a legal range of output values. When the input values are invalid, or it cannot provide the expected output values, you should throw an exception.

    Note that there is a slippery point here - should validation (of user input) errors also be thrown as exceptions? Some schools of thought say no (Microsoft included), some say yes. Your call. Each approach has its benefits and drawbacks, and it's up to you to decide how you will structure your code.

    A rule of thumb for catching exceptions is - you should only catch exceptions that you can handle. Now, this is also slippery. Is displaying the error message to the user also "handling" it? But what if it's the infamous StackOverflowException or OutOfMemoryException? You can hardly display anything then. And those might not be the only exceptions that can leave the whole system in an unusable state. So again - your call.

提交回复
热议问题