What is the difference between an error and an exception in .NET?

前端 未结 8 2025
说谎
说谎 2021-02-02 12:28

Could you please explain to me what the difference is between an error and an exception?

8条回答
  •  不要未来只要你来
    2021-02-02 12:54

    An exception is a class that takes advantage of language semantics. As others have stated, exceptions interrupt execution up the stack until caught. An exception can be used to convey an error, but more generally is used to convey that something exceptional has occurred.

    Errors, on the other hand, can be exceptional or not.

    There are several kinds of errors:

    • User error - this should be handled without an exception
    • Syntax error - this shouldn't compile in statically typed languages (in dynamic languages, they're a little harder to discover)
    • Runtime error - this will either result in an exception, or silently fail (usually creating unexpected results)

    Really, exceptions should be limited to handling runtime errors, since a user inputting bad data is not "exceptional." To handle user errors, you should take the following approaches:

    • Prevent bad data from being input (front-end validation)
    • Prevent bad data from being persisted (back-end validation)

    Exceptions should be used as a "last line of defense" for user error. If you're writing a persistence layer, you can rely on exceptions to ensure that bad data that falls through validation does not get persisted. You should, however, fix any of these by putting a fix in the validation that prevents the error from occurring in the first place.

提交回复
热议问题