tags:

views:

198

answers:

6

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

+12  A: 

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();".

John Saunders
I don't know if I would say there is a problem with error codes, rather that, with exceptions you can leverage the fact that "someone" will have to handle the exception whereas an error can be disregarded.Exceptions are not better than errors. They are just what they are called, exceptions. Something exceptional has occurred and is interrupting the process flow.
Lucas B
@LucasB: the fact that error codes can be ignored _is_ the problem with error codes. That plus the fact they are semantically lightweight.
John Saunders
Semantically, an exception isn't necessarily an error, it's just something that should interrupt the "normal" code path in favor of an "exceptional" one. Most of the time that means the same thing as "error", but then we can get into semantic debates about what "error" means. "System errors", "programmer errors", and "user errors" are all conceptually "errors", but in user interface code a "user error" like entering an invalid value into a text box is not usually considered "exceptional" enough to throw an exception.
Daniel Pryden
I might clarify that you can decide to *unintentionally* ignore error codes. You can still ignore exceptions by just using a try/catch with no action within the catch block.
CrimsonX
@CrimsonX: exactly. The fact that you're ignoring exceptions is obvious by looking at the code, either with human eyes, or with a tool.
John Saunders
+6  A: 

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.

Michael Meadows
I would argue that user errors might be handled with exceptions internally (say, a Verify method that returns a custom exception). Those exceptions would be caught and reported in a friendly manner, though. This isn't the normal flow of control, nor is it likely to have performance implications.
TrueWill
@TrueWill - I agree. I had a need for using exception catching/rethrowing as flow control "paradigm" once. It was an exotic case but, I was glad something existed to let me accomplish what I needed to ... @Michael, no downvote, but I don't entirely agree either.
overslacked
I guess I didn't state it well enough. Exceptions shouldn't be the primary mechanism used ensure proper input. If bad data passes validation, than it becomes an exceptional case. That's what I meant when I said "an exception can be used to convey an error." I'll make the "can" italics.
Michael Meadows
@TrueWill - I wish it were possible to downvote a comment. ;) User errors should not be handled with an exception, because user error is not an exceptional condition. User error happens all the time. Think of improper input in a text box that must be validated. Exceptions have a large impact on performance, and should not be used to handle conditions which should be part of your design and requirements.
Nick
@Nick @TrueWill I think you're both right. In the case that the user inputs bad data, it's not exceptional, but if the programmer lets that through into the persistence layer, then it does become exceptional. At the point that bad data is being saved, the code doesn't know how to respond to the fact that some of the data _should not_ be saved, and therefore an exceptional case has been created. **edit** changed "than" to "then". I hate when I mix those up.
Michael Meadows
@Michael - Yes and no. Your point is well taken, and correct. But semantically, I would argue that once bad data gets down to a persistence layer, it's not a user error anymore... its a programmer error. ;-) In other words, it should never have gotten there in the first place. @TrueWill's example of a Verify method implies UI validation, which should not use exceptions to report problems.
Nick
@Nick - I wish Exception had been named Failure. Exceptions are for error conditions. While you do need to consider performance, exceptions are seldom the true bottlenecks. I'm not advocating using exceptions for UI validation; I'm just saying I wouldn't dismiss it out of hand.
TrueWill
A: 

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

Asad Butt
A: 

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).

TrueWill
+1  A: 

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

MatteS
I like this, so I upvoted. However, you do have to already understand both exceptions and errors (well, error codes, as you say), in order for it to appeal. So top marks for pithiness, but I'm not sure it really answers the question :)
ChrisA
+1  A: 

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.

Sunny