views:

620

answers:

11

It's my understanding that common wisdom says to only use exceptions for truly exceptional conditions (In fact, I've seen that statement here at SO several times).

However, Krzysztof Cwalina says:

One of the biggest misconceptions about exceptions is that they are for “exceptional conditions.” The reality is that they are for communicating error conditions. From a framework design perspective, there is no such thing as an “exceptional condition”. Whether a condition is exceptional or not depends on the context of usage, --- but reusable libraries rarely know how they will be used. For example, OutOfMemoryException might be exceptional for a simple data entry application; it’s not so exceptional for applications doing their own memory management (e.g. SQL server). In other words, one man’s exceptional condition is another man’s chronic condition.

He then also goes on to say that exceptions should be used for:

  • Usage errors
  • Program errors
  • System failures

Considering Krzysztof Cwalina is the PM for the CLR team at MS I ask: What do you think of his statement?

+8  A: 

For people who write frameworks, perhaps it's interesting.

For the rest of us, it's confusing (and possibly useless.) For ordinary applications, exceptions have to be set aside as "exceptional" situations. Exceptions interrupt the ordinary sequential presentation of your program.

You should be circumspect about breaking the ordinary top-to-bottom sequential processing of your program. The exception handling is -- intentionally -- hard to read. Therefore, reserve exceptions for things that are outside the standard scenarios.

Example: Don't use exceptions to validate user input. People make input mistakes all the time. That's not exceptional, that's why we write software. That's what if-statements are for.

When your application gets an OutOfMemory exception, there's no point in catching it. That's exceptional. The "sequential execution" assumption is out the window. Your application is doomed, just crash and hope that your RDBMS transaction finishes before you crash.

S.Lott
Hey man, I don't mean to be rude, but you don't support your statement with any reasons.
Esteban Araya
That's correct, for frameworks or system development the exception handling is quite different than for applications.
OscarRyz
@Esteban Araya: good point -- I omitted mentioning that the top-to-bottom sequential text is important.
S.Lott
@S.Lott: Thanks for the added points. However, I don't think sequential presentation is necessarily good - especially in an event driven environment. Also, I don't think exception handling is hard to read. But that's just me. Thanks again!
Esteban Araya
"I don't think sequential presentation is necessarily good". Interesting. Since most programming languages use sequential presentation, either with ;'s or \n's to string statements sequentially.
S.Lott
@S.Lott: Sorry; I mean't "ordinary top-to-bottom sequential processing of your program". Sequential programming is SO not object oriented. :)
Esteban Araya
+1  A: 

I've been wondering about this myself. What do we mean by "exceptional"? Maybe there's no strict definition, but are there any rules of thumb that we can use to decide what's exceptional, in a given context?

For example, would it be fair to say that an "exceptional" condition is one that violates the contract of a function?

JW
A: 

KCwalina has a point. It will be good to identify cases where the code will fail (upto a limit)

I agree with S.Lott that sometimes validating is better than to throw Exception. Having said that, OutOfMemory is not what you might expect in your application (unless it is allocating a large memory & needs memory to go ahead).

I think, it depends on the domain of the application.

shahkalpesh
+9  A: 

This sounds over-simplistic, but I think it makes sense to simply use exceptions where they are appropriate. In languages like Java and Python, exceptions are very common, especially in certain situations. Exceptions are appropriate for the type of error you want to bubble up through a code path and force the developer to explicitly catch. In my own coding, I consider the right time to add an exception when the error either can't be ignored, or it's simply more elegant to throw an exception instead of returning an error value to a function call etc.

Some of the most appropriate places for exceptions that I can think of offhand:

  • NotImplementedException - very appropriate way of designating that a particular method or function isn't available, rather than simply returning without doing anything.
  • OutOfMemory exceptions - it's difficult to imagine a better way of handling this type of error, since it represents a process-wide or OS-wide memory allocation failure. This is essential to deal with, of course!
  • NullPointerException - Accessing a null variable is a programmer mistake, and IMO this is another good place to force an error to bubble to the surface
  • ArrayIndexException - In an unforgiving language like C, buffer overflows are disastrous. Nicer languages might return a null value of some type, or in some implementations, even wrap around the array. In my opinion, throwing an exception is a much more elegant response.

This is by no means a comprehensive list, but hopefully it illustrates the point. Use exceptions where they are elegant and logical. As always with programming, the right tool for the right job is good advice. There's no point going exception-crazy for nothing, but it's equally unwise to completely ignore a powerful and elegant tool at your disposal.

Jay
+1, I enjoy implementing exceptions in my own code, in order to flag items that require work (i.e.: NotImplemented), or to get more detailed error reporting from specific errors (i.e.: File IO operations). I leave them to bubble up to a certain level and then email them to myself. Good for testing!
Pat
Agreed, error communication by throwing exceptions has its place.
jpoh
+4  A: 

Since I usually program in Python, and in that language exceptions are everywhere, to me an exception may represent anything from a system error to a completely legitimate condition.

For example, the "pythonic" way to check if a string contains an integer is to try int(theString) and see if it raises an exception. Is that an "exceptional error"?

Again, in Python the for loop is always thought of as acting on an iterator, and an iterator must raise a 'StopIteration' exception when it finishes its job (the for loop catches that exception). Is that "exceptional" by any means?

Federico Ramponi
I frequently use Java's Integer.parseInt(String var) in the same way.
slim
+1 Came here to say "Depends on the language. In Python...."
J.T. Hurley
Note that in Python this may work, but in Java, C++, VB and C#, catching an exception is very slow, between 40 to 400 times slower than an if-statement can be. Depending on your input (do you expect an occasional non-number, or will it happen often), this may or may not be good design. Which is again why exceptions should be used when the expected situation is just that: exceptional as compared to normal.
Abel
+3  A: 

I think the closer to the ground are you are the less appropriate exceptions as a means of error communication become. At a higher abstraction such as in Java or .net, an exception may make for an elegant way to pass error messages to your callers. This however is not the case in C. This is also a framework vs api design decision.

Aaron Fischer
+4  A: 

It is indeed difficult to know what exactly construes an "exceptional condition" which warrants the use of an exception in a program.

One instance that is very helpful for using communicating the cause of errors. As the quote from Krzysztof Cwalina mentions:

One of the biggest misconceptions about exceptions is that they are for “exceptional conditions.” The reality is that they are for communicating error conditions.

To give a concrete example, say we have a getHeader(File f) method that is reading some header from a file and returns a FileHeader object.

There can be several problems which can arise from trying to read data from a disk. Perhaps the file specified doesn't exist, file contains data that can't be read, unexpected disk access errors, running out of memory, etc. Having multiple means of failure means that there should be multiple ways to report what went wrong.

If exceptions weren't used, but there was a need to communicate the kind of error that occurred, with the current method signature, the best we can do is to return a null. Since getting a null isn't very informative, the best communication we get from that result is that "some kind of error happened, so we couldn't continue, sorry." -- It doesn't communicate the cause of the error.

(Or alternatively, we may have class constants for FileHeader objects which indicate FileNotFound conditions and such, emulating error codes, but that really reeks of having a boolean type with TRUE, FALSE, FILE_NOT_FOUND.)

If we had gotten a FileNotFound or DeviceNotReady exception (hypothetical), at least we know what the source of the error was, and if this was an end user application, we could handle the error in ways to solve the problem.

Using the exception mechanism gives a means of communication that doesn't require a fallback to using error codes for notification of conditions that aren't within the normal flow of execution.

However, that doesn't mean that everything should be handled by exceptions. As pointed out by S.Lott:

Don't use exceptions to validate user input, for example. People make mistakes all the time. That's what if-statements are for.

That's one thing that can't be stressed enough. One of the dangers of not knowing when exactly to use exceptions is the tendency to go exception-happy; using exceptions where input validation would suffice.

There's really no point in defining and throwing a InvalidUserInput exception when all that is required to deal in such a situation is to notify the user of what is expected as input.

Also, it should be noted that user input is expected to have faulty input at some point. It's a defensive measure to validate input before handing off input from the outside world to the internals of the program.

It's a little bit difficult to decide what is exceptional and what is not.

coobird
A: 

I think there are a couple of good reasons why exceptions should be used to catch unexpected problems.

Firstly, they create an object to encapsulate the exception, which by definition must make it a lot more expensive than processing a simple if-statement. As a Java example, you should call File.exists() rather than routinely expecting and handling a FileNotFoundException.

Secondly, exceptions that are caught outside the current method (or maybe even class) make the code much harder to read than if the handling is all there in in the one method.

Having said that, I personally love exceptions. They relieve you of the need of explicitly handling all of those may-happen-but-probably-never-will type errors, which cause you to repetitively write print-an-error-and-abort-on-non-zero-return-code handling of every method call.

My bottom line is... if you can reasonably expect it to happen then it's part of your application and you should code for it. Anything else is an exception.

Greg Cottman
A: 

The statement from Krzysztof Cwalina is a little misleading. The original statement refers 'exceptional conditions', for me it is natural that I am the one who defines what's exceptional or not. Nevertheless, I think the message passed through OK, since I think we are all talking about 'developer' exceptions.

Exceptions are great for communication, but with a little hierarchy design they are also great for some separation of concerns, specially between layers (DAO, Business, etc). Of course, this is only useful if you treat these exceptions differently.

A nice example of hierarchy is spring's data access exception hierarchy.

Miguel Ping
A: 

If you practice "tell, don't ask" then an exception is just the way a program says "I can't do that". It is "exceptional" in that you say "do X" and it cannot do X. A simple error-handling situation. In some languages it is quite common to work this way, in Java and C++ people have other opinions because exceptions become quite costly.

General: exception just means "I can't"

Pragmatic: ... if you can afford to work that way in your language.

Citizenship: ... and your team allows it.

Tim Ottinger
+2  A: 

I found this article very useful:

http://today.java.net/pub/a/today/2006/04/06/exception-handling-antipatterns.html

opyate
Nice link - thanks.
Jonathan Leffler