Related
I have inherited a suite of business objects, which are working rather well. It looks as though it's based on the CSLA framework by Rockford Lhotka, but there is one very annoying issue. When the business object does a load, it throws an exception. So, if it tries to load some data that isn't available in the database, you get an exception thrown. Is this good design?
I've been having a debate with a co-worker about this very topic lately.
It's my assertion that a situation where a method you expect to do X does not do X is the very definition of an exception.
What you chose to do with that exception is another story. You can choose to handle it internally in your code or you can choose to defer the handling of that exception to a higher level in your code.
I will agree that it is always better to handle an exception if it at all makes sense to do so when and where it occurs rather than deferring it to a higher level of code.
That said I also believe that in lower levels of code it can make some sense to defer the handling of these exceptions to the higher levels of code. This provides the higher level of code more flexibility in how it wants to handle these situations and it also gives that higher level of code insight into what occured.
If for example your retrieving data from a database and building an object for use in your application you could conceivably have several things happen:
Return an Object as expected.
Be unable to connect to the database.
Not find the data you expect to find.
You could handle the exceptions 2 and 3 by simply returning an empty object or null but then the higher level code doesn't know why the information it requested was not returned. This would require some secondary pattern in which to notify the higher level of what occurred.
Alternatively I assert that you could create a custom exception with a message field in which to pass back the exception event which occurred. Forcing your higher level code to handle those situations as it sees appropriate.
In my opinion the later can be more flexible but does require the higher level code to know it needs to handle the exceptions which should be well documented so that its clear a method can throw certain exceptions.
Note: I am not an expert, I do not claim to be, I am sharing my opinion after encouragement from my peer whom I have been debating this topic with.
IMHO, Exceptions are for exceptional cases -- missing data is usually not exceptional, unless its on a primary key, or other non-null field.
It depends on the impact to the application of the data being missing. If the application cannot reasonably continue without the data, then it is an exceptional case and an exception is warranted. If it is relatively normal for the data to be missing (and especially if the caller is expected to handle the exception and carry on), then that is a use of exceptions that is a bad design.
i have some business logic that traps some logically invalid situations, e.g. trying to reverse a transaction that was already reversed. In this case the correct action is to inform the user:
Transaction already reversed
or
Cannot reverse a reversing transaction
or
You do not have permission to reverse transactions
or
This transaction is on a session that has already been closed
or
This transaction is too old to be reversed
The question is, how do i communicate these exceptional cases back to the calling code, so they can show the user?
Do i create a separate exception for each case:
catch (ETransactionAlreadyReversedException)
MessageBox.Show('Transaction already reversed')
catch (EReversingAReversingTransactionException)
MessageBox.Show('Cannot reverse a reversing transaction')
catch (ENoPermissionToReverseTranasctionException)
MessageBox.Show('You do not have permission to reverse transactions')
catch (ECannotReverseTransactionOnAlredyClosedSessionException)
MessageBox.Show('This transaction is on a session that has already been closed')
catch (ECannotReverseTooOldTransactionException)
MessageBox.Show('This transaction is too old to be reversed')
Downside for this is that when there's a new logical case to show the user:
Tranasctions created by NSL cannot be reversed
i don't simply show the user a message, and instead it leaks out as an unhandled excpetion, when really it should be handled with another MessageBox.
The alternative is to create a single exception class:
`EReverseTransactionException`
With the understanding that any exception of this type is a logical check, that should be handled with a message box:
catch (EReverseTransactionException)
But it's still understood that any other exceptions, ones that involve, for example, an memory ECC parity error, continue unhandled.
In other words, i don't convert all errors that can be thrown by the ReverseTransaction() method into EReverseTransactionException, only ones that are logically invalid cause of the user.
I find that there are various broad categories of exception:
TransientException - what you just tried didn't work, but if your try again it might. Used for cases such as Database not currently available.
InvalidRequestException - you just asked for something that can't be done (Your examples fit here)
SystemException - The system is sick, we've forgotten everything you just said, your session is dead, you need to start all over again.
I would have these three main types of exception and catch each of them, there being obvious specific actions in each case. All my exceptions derive from these three types.
To me the rule of thumb is whether it is useful for the user to see the exact error message. This varies wildly between different types of applications. A desktop app used by millions of "average users" is a very different case from an enterprise web app used by a coupe hundred trained professionals.
For the former, it might be better to display a generic "system error, please restart" type message instead of technical details which the user doesn't understand and is usually not bothered to forward to the support department anyway (unless it can be done with the press of a button).
Our project is of the latter case, and the users typically forward problems to support. So we try to improve the error messages to contain information relevant to the support team. Since ours is a legacy app, we are much less worried about memory parity errors than plain null pointer exceptions and logical errors in the code though.
As for the number of distinct exception types, I am a fan of simplicity so I try to get by with the minimum necessary number of exception types, one for each distinct error category. What constitutes a separate category is also defined by how and when that bug can occur, and how and when it is handled. Since your cases above all are associated with the same use case, I would use a single exception type with specific detail messages.
I recommend the single exception with a cause identifier. The cause itself could be an exception which is wrapped in your user exception, although I would consider this mostly for debugging purposes, or as a means to derive additional details.
Your main exception includes an identifier, which identifies succinctly what the user has done wrong. It can be used as the basis for retrieving localized messages to show the user, for linking to user documentation, help, troubleshooting, and other assistance.
The message ID is also useful as an error code which can be used when reporting problems and for documenting solutions in support documentation for your support team.
I use a superclass for all user-level exceptions that allow the use of an ID to identify the situation or cause. All the IDs are documented, and each has at least one test cases to provoke the exception.
Are you deriving all of your exceptions from the base Exception (or EException or whatever the equivalent is in your language?)
I handle this by deriving all business logic errors from a ClientException (the user provided invalid input) or BusinessRuleException (input was valid but would unwittingly violate some important business or domain rule).
Any exception that derives from either of these roots can be caught and displayed to the user. Other exceptions go to the global exception handler, unless the code knows specifically how to handle them.
(Actually, that's not entirely accurate. What really happens is that the global exception handler itself recognizes these exceptions and handles them differently. But the principle is the same.)
You should create separate exceptions when you need (or expect to need) different types of behavior to handle the different exceptions. If you just want different messages displayed, but the basic behavior will be the same for all of them, then you probably just want to derive one exception class from std::runtime_error:
class transaction_error : public std::runtime_error {
public:
transaction_error(std::string const &caption) : std::runtime_error(caption) {}
};
which you'd throw something like:
throw transaction_error("Transaction already reversed");
...and catch something like:
try {
execute_transaction(transaction_data);
}
catch(transaction_error const &e) {
MessageBox(NULL, e->what(), "Transaction Error", MB_OK);
}
When should you throw a custom exception?
e.g. I have some code that connects to a server. The code that connects to the server throws an IOException when it fails to connect. In the context of the method it's called, this is fine. It's also fine in the network code.
But as this represents not having a connection (and therefore not working) the exception goes all the way up to the ui. At this stage, an IOException is very ambigous. Something like NoConnectionException would be better.
So, my question is:
At what stage should you catch an exception to instead throw another (custom) exception that better fits the abstraction?
I would expect exceptions to talk in terms of what I've asked the originating method to do. e.g.
read -> ReadException
connect -> ConnectException
buildPortfolio -> FailedToBuildPortfolioException
etc. This abstracts away what's going on under the covers (i.e. are you connecting via sockets etc.). As a general rule, when I create an interface for a component, I often create a corresponding exception or set of exceptions. My interface will be called Component, and my exceptions are usually ComponentException (e.g. RateSource and RateSourceException). It's consistent and easy to export to different projects as a complete component set.
The downside is that you create quite a lot of exceptions, and you may have to perform quite a lot of translations. The upside is that (as you've identified) you get little to no abstraction leakage.
At some point during the hierarchy of method calls (and thus exceptions) you may decide that no recovery can take place (or it's at an inappropriate place) and translate to unchecked exceptions to be handled later.
I know this is tagged as "language-agnostic", but I don't think it really is. Coming from a C++ perspective, I expect very few basic operations to throw an exception - the C++ Standard Library only uses exceptions in a very few places. So my own code is often the first place where exceptions can be generated. In that code, I like a very flat hierarchy - I don't want to be messing with hundreds of catch() clauses later in the code, and have never understood Java and C#'s apparent obsession with creating Baroque heirarchies of class and namespace.
So, for my C++ code - one type of exception, containing a meaningful error message, per library. And one for the final executable.
I think there are two questions hidden here:
a) When should one hide an exception behind a different exception.
b) When should one use a custom exception for this.
a) I'd say: when ever an exception travels across the border of two layers in the application, it should get hidden behind an exception that is more apropriate for the new layer.
Example: because you are doing some remote stuff, you get a ConnectionWhatEverException.
But the caller shouldn't be aware of Connection problems. Since he just wants to get some service performed, so he gets a ServiceOutOfOrderException. The reason for this is: Inside the layer, doing remoting, you might to do something usefull with a ConnectionException (retry, write into a backout queue ..). Once you left that layer, nobody knows how to handle a ConnectionException. But they should be able to decide, what do do, when the Service does not work.
b) When there is no matching existing Exception. There are a couple of useful Exception in Java for example. I use IllegalState and IllegalArgument quite often. A strong argument for a new exception class is, if you have some useful context to provide. For example the name of the service that failed could be an argument of a ServiceFailedException. Just don't create a class for every method call, or anything to that effect. 100 Exception classes aren't a problem, as long as they have different behavior (i.e. at least different fields). If they differ only by name and reside on the same abstraction level, make them one Exception, and put the different names in the message or a single field of that exception class.
c) At least in java there is the discussion about checked exceptions. I wrap those directly in an unchecked one, because I hate the checked kind. But that is more an opinion then advice.
Is there any case where you would get NoConnectionException which isn't caused by an IO issue? Conversely, is knowing whether the cause is IO based or not going to help the client recover sensibly?
When should you throw a custom exception?
I. When you can provide more (diagnostic) information.
Note: this additional information may not be available at the place where the original exception (IOException) was thrown. Progressive layers of abstractions may have more information to add like what were you trying to do which led to this exception?
II. When you must not expose implementation details: i.e. you want the (illusion of?) abstraction to continue.
This may be important when the underlying implementation mechanism can change. Wrapping the underlying exception in a custom exception is a good way of insulating your clients from implementation details (by lifting the level of abstraction)
III. Both I and II
NOTE: Furthermore your clients should be able to tune into the exact level of information they are interested in or rather they should be able to tune out anything they are not interested in. So it's a good idea to derive your custom exceptions from IOException.
Should a business rule violation throw an exception?
No. It's part of normal conditional-handling logic in the program (and often just a disguised form of user error).
It depends on what the business rule is, IMO. I would venture to say "not usually" but I'd view it on a case-by-case basis. I don't think there is any one answer, as different business rules might warrant it while others might not.
First, a couple of quotes from chapter 18 of Applied Microsoft .NET Framework Programming (page 402) by Jeffrey Richter:
"Another common misconception is that an 'exception' identifies an 'error'."
"An exception is the violation of a programmatic interface's implicit assumptions."
If I'm inferring correctly from your question that a business rule violation would be data that falls outside a certain range (for example), this is an error that you could handle with a conditional as #ahockley suggested. Based on the definition of an exception from Richter, the appropriate use of an exception would be if your code wasn't able to retrieve a business rule from whatever repository you're using. Being able to retrieve a business rule would be a reasonable implicit assumption for that interface to have, so an exception should be thrown if this assumption was violated.
One good example of Richter's first quote (exception != error) is the ThreadAbortException. If you call Response.Redirect(url) (in ASP.NET), a ThreadAbortException is thrown even though the redirect succeeds. Why? The implicit assumption of ASP.NET page execution is that a page will execute completely. Response.Redirect(url) violates this assumption, hence the exception.
Because of the way I do my validation and my use of LINQtoSQL for ORM, yes. If an entity fails validation on a business rule during the OnValidate method, the only way to notify the calling code is to throw an Exception. In this case, I throw a custom DataValidationException. Using the OnValidate method hook in a partial class implementation of the entity makes it possible for me to enforce validation on update/insert so only valid data gets saved to the database.
EDIT I should make it clear that I typically do validation of user input at the client so the persistence layer validation is typically more insurance and rarely, if ever, fails. I don't handle the client-side validation as exceptions, but rather with conditional logic.
Do you mean, for example, that a value is supposed to be in the range 0-99 but somehow ended up being 105?
If it's coming from the user it's a matter of validation. Whether it is handled using exceptions or not depends on the idioms of your language.
If it's coming from your data store then yes, it seems reasonable to throw an exception. It means you have bad data and you need to figure out how it got there and prevent it from happening again.
No
Violating a business rule is a BUSINESS issue where an exception is a technical one. Violating a business rule is something that the system should regard as normal operation and for which it should have a programmed response, not an exception.
As an alternative view to most of the answers...
It can be useful to throw exceptions from the business logic, particularly if they are cuased by a failure in validation. If you are expecting an object and you get a null, it suggests that some problem has evaded detection in the user interface (or other interface). It may be completely valid to throw exceptions at this point. Indeed, you may decide to place this type of validation in the business logic when there are multiple interfaces.
Throwing exceptions in some languages / frameworks (I am thinking .NET) can be costly but this should not immediately worry you. It does mean that, at the name suggests, they are used for exceptional circumstances and not as part of the standard flow of a program. You certainly shouldn't throw an exception just to exit a method. You should also consider a graceful recovery where possible that may not include throwing an exception.
So, summing up... It depends...
I would say not normally but I don't think you can say never.
For instance it depends on who/what is handling of the failed rule. If it is a user interface/user then I would use conditional logic to deal with the failure appropriately. However if it is a business rule failure in, for instance, a faceless process that logs any errors to an event log which will be monitored by for a technical resource then an exception may be just as appropriate. In this later case an appropriately named exception can be just as helpful as a nicely formatted message.
Business rules could throw exception but they shouldn't.
If you have another way to communicate information about common and predictable validation error, you should use it.
Throwing exceptions can be computationally intensive, they are outside of the norm. For example in .net you have performance counters that are incremented - that is a heavyweight acitivty and so not something you would want to do instead of a simple conditional.
It really depends on what it is and where it is.
If it's some data coming from the user then as levand said it's a matter of validation. Validation can turn up both successful and failed, both are expected options with clear further action scenarios.
If it's something like method execution errors it could be a better idea to throw an exception and stop right there before more harm is done (such as producing inconsistencies in the database).
It is often a matter of perspective and your application design.
Usualy I put the condition in a Specification object that implements
bool IsVerfiedBy(T entity);
So you can check the condition without exception.
If there is a place in your code where the specification should be verified beforehand, you can throw an exception because this is a prerequisit of you function.
For instance if your entity must be in a specific state before persistance, throw an exception when the specification is not verified, but use the specification before persisting so that the exception does not happen.
Business rules should not throw an exception, unless they are used to validate parameters of some API (i.e.: checking requests validity) or in unit tests (i.e.: using business rules to simplify .NET unit tests).
Generally business rules output error and warning messages to the validation scope, though.
There is good guidance in the wiki for the book 97 Things Every Project Manager Should Know, in particular in the chapter Distinguish Business Exceptions from Technical.
So, if your programming language supports it, the best thing is to create custom exception classes so the their workflow and handling can be different from technical exceptions.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
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?
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.
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.
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.
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?
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.
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.
Here is the definition for exception: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
Therefore, to answer your question, no. Exceptions are for disruptive events, which may or may not be exceptional. I love this definition, it's simple and works every time - if you buy into exceptions like I do. E.g., a user submits an incorrect un/pw, or you have an illegal argument/bad user input. Throwing an exception here is the most straightforward way of solving these problems, which are disruptive, but not exceptional, nor even unanticipated.
They probably should have been called disruptions, but that boat has sailed.
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.
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?
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.
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.
I think he is right. Take a look at number parsing in java. You cant even check input string before parsing. You are forced to parse and retrieve NFE if something went wrong. Is parse failure something exceptional? I think no.
I certainly believe exceptions should be used only if you have an exceptional condition.
The trouble is in the definition of "exceptional". Here is mine:
A condition is exceptional if it is outside the assumed normal
behaviour of the part of the system that raises the exception.
This has some implications:
Exceptional depends on your assumptions. If a function assumes that it is passed valid parameters, then throwing an IllegalArgumentException is OK. However if a function's contract says that it will correct input errors in input in some way, then this usage is "normal" and it shouldn't throw an exception on an input error.
Exceptional depends on sub-system layering. A network IO function could certainly raise an exception if the network is discommented, as it assumes a valid connection. A ESB-based message broker however would be expected to handle dropped connections, so if it used such a network IO function internally then it would need to catch and handle the error appropriately. In case it isn't obvious, try/catch is effectively equivalent to a subsystem saying "a condition which is exceptional for one of my components is actually considered normal by me, so I need to handle it".
The saying that exceptions should be used for exceptional circumstances is used in "Effective Java Second Edition": one of the best java books.
The trouble is that this is taken out of context. When the author states that exceptions should be exceptional, he had just shown an example of using exceptions to terminate a while loop - a bad exception use. To quote:
exceptions are, as their name implies, to
be used only for exceptional conditions; they should never be used for ordinary
control flow.
So it all depends on your definition of "exception condition". Taken out of context you can imply that it should very rarely be used.
Using exceptions in place of returning error codes is good, while using them in order to implement a "clever" or "faster" technique is not good. That's usually what is meant by "exceptional condition".
Checked exception - minor errors that aren't bugs and shouldn't halt execution. ex. IO or file parsing
Unchecked exception - programming "bug" that disobeys a method contract - ex. OutOfBoundsException. OR a error that makes continuing of execution a very bad idea - ex IO or file parsing of a very important file. Perhaps a config file.
What it comes down to is what tool is needed to do the job.
Exceptions are a very powerful tool. Before using them ask if you need this power and the complexity that comes with it.
Exceptions may appear simple, because you know that when the line with the exception is hit everything comes to a halt. What happens from here though?
Will an uncaught exception occur?
Will the exception be caught by global error handling?
Will the exception be handled by more nested and detailed error handling?
You have to know everything up the stack to know what that exception will do. This violates the concept of independence. That method now is dependent on error handling to do what you expect it to.
If I have a method I shouldn't care what is outside of that method. I should only care what the input is, how to process it, and how to return the response.
When you use an exception you are essentially saying, I don't care what happens from here, something went wrong and I don't want it getting any worse, do whatever needs to be done to mitigate the issue.
Now if you care about how to handle the error, you will do some more thinking and build that into the interface of the method e.g. if you are attempting to find some object possibly return the default of that object if one can't be found rather than throwing some exception like "Object not found".
When you build error handling into your methods interface, not only is that method's signature more descriptive of what it can do, but it places the responsibility of how to handle the error on the caller of the method. The caller method may be able to work through it or not, and it would report again up the chain if not. Eventually you will reach the application's entry point. Now it would be appropriate to throw an exception, since you better have a good understanding of how exceptions will be handled if you're working with the applications public interface.
Let me give you an example of my error handling for a web service.
Level 1. Global error handling in global.asax - That's the safety net to prevent uncaught exceptions. This should never intentionally be reached.
Level 2. Web service method - Wrapped in a try/catch to guarantee it will always comply with its json interface.
Level 3. Worker methods - These get data, process it, and return it raw to the web service method.
In the worker methods it's not right to throw an exception. Yes I have nested web service method error handling, but that method can be used in other places where this may not exist.
Instead if a worker method is used to get a record and the record can't be found, it just returns null. The web service method checks the response and when it finds null it knows it can't continue. The web service method knows it has error handling to return json so throwing an exception will just return the details in json of what happened. From a client's perspective it's great that it got packaged into json that can be easily parsed.
You see each piece just knows what it needs to do and does it. When you throw an exception in the mix you hijack the applications flow. Not only does this lead to hard to follow code, but the response to abusing exceptions is the try/catch. Now you are more likely to abuse another very powerful tool.
All too often I see a try/catch catching everything in the middle of an a application, because the developer got scared a method they use is more complex than it appears.