开发者

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

开发者 https://www.devze.com 2022-12-22 23:23 出处:网络
Could you please explain to me what the difference is between a开发者_C百科n error and an exception?An exception is a class that takes advantage of language semantics.As others have stated, exceptions

Could you please explain to me what the difference is between a开发者_C百科n error and an exception?


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.


An exception is an object of a type deriving from the System.Exception class. It is used in a throw statement to transfer control to a catch clause in a try block somewhere further up the call stack.

An error is just some code or message that you're meant to interpret. The problem with error codes is that you can decide to ignore them:

MethodThatReturnsAnError();
SomeCodeThatShouldNotExecuteOnError();

That call will simply ignore the error code if one is returned. However:

MethodThatThrowsAnException();
SomeCodeThatShouldNotExecuteOnError();

This cannot be ignored, and will transfer control up the stack, past "SomeCodeThatShouldNotExecuteOnError();".


Exceptions you have to write code to ignore. Error codes you have to write code to not ignore.


Usually, I classify them as:

Error - is a known workflow within the application. For example: Username not provided during authentication is an error.
The application can handle these situation & will be able to show friendly messages to the user to prompt for proper input and/or process the data in a different.

Exception - is usually throw when going out of your system and/or something unexpected happens in the application. For example: opening a file handle might throw an exception due to insufficient rights or the file not existing.
Usually in this case, the application can catch these exception and/or write a generic handler to handle all the exceptions in the system.

As a rule of thumb, if you know a particular case exists due to which the application cannot proceed working, label it as an error & handle the case gracefully.

All remaining 'unknown-unknows' can then fall into the category of Exceptions.

HTH.


If no exception handler for a given exception is present, the program stops executing with an error message.

Unhandled Exceptions are Errors. So All Errors are Exceptions but the reverse is not true. Exception Handlings technique handles the Exception/Unexpected Situations(Errors), While errors are Situations which we havenot expected to occur so explicitly we have to take care of them by redirectly the User(s) to some static HTML Page & capturing it into Logs & come up with a Solution for the Error occured.

Errors Can Occur at 2 Levels

  • Page Level( use ErrorPage Attribute at the page Directive)
  • Application Level(Need to be Handled in web.config)

Compilation CustomError ... CustomError error.... error Compilation Note- Page Level Error handling overrides the Application Level Error Handling.

Exception Handling:->

  • Locally (Method Level)

    • Page Level
    • Aplication Level
    • Http module Level.

    Will Link-> http://msdn.microsoft.com/en-us/library/ms173160(v=vs.80).aspx


Exceptions are a way of reporting and handling execution failures. In other words, they are for communicating error conditions (paraphrasing Krzysztof Cwalina in the book Framework Design Guidelines).


Exception: When a step in some action fails, all the subsequent steps in that action are simply NOT executed. This is where exceptions shine.

Error: is when, like in the first case you want to halt execution of the current code, but before you do you need to free any resources previously allocated.


Having that said,

Exception class has HResult property. HRESULT is a 32-bit value, divided into three different fields: a severity code, a facility code, and an error code.

Have a look at this post, will help you understand better

  • Error codes or Exceptions?


Errors are events. Exception class represents errors that occur during application execution (runtime) and provides a mechanism to handle them using try catch blocks. Errors could be runtime or compiler error/s.

Examples of error events: HttpApplication.Error Event of System.Web dll, FileSystemWatcher.Error Event of System.IO Both dlls have same definition of Error event

public event EventHandler Error

From .Net Framework 4.5 documentation https://msdn.microsoft.com/en-us/library/system.exception(v=vs.110).aspx

Exception class represents errors that occur during application execution.

Errors and exceptions

Run-time errors can occur for a variety of reasons. However, not all errors should be handled as exceptions in your code. Here are some categories of errors that can occur at run time and the appropriate ways to respond to them.

Usage errors. A usage error represents an error in program logic that can result in an exception. However, the error should be addressed not through exception handling but by modifying the faulty code.

Program errors. A program error is a run-time error that cannot necessarily be avoided by writing bug-free code.

In some cases, a program error may reflect an expected or routine error condition. In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation.

In other cases, a program error reflects an unexpected error condition that can be handled in your code.

System failures. A system failure is a run-time error that cannot be handled programmatically in a meaningful way. For example, any method can throw an OutOfMemoryException exception if the common language runtime is unable to allocate additional memory. Ordinarily, system failures are not handled by using exception handling. Instead, you may be able to use an event such as AppDomain.UnhandledException and call the Environment.FailFast method to log exception information and notify the user of the failure before the application terminates.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号