Why is it a "bad idea" to throw your own exceptions? - exception

Why is it a "bad idea" to throw your own exceptions?
found here

In general, it is perfectly fine to throw your own exceptions. Perhaps what you meant to ask was "When is it not necessarily a good idea to throw my own exception?"
One case is when you should be throwing a standard exception. For example, if your method takes a file name and is supposed to return a file, you should probably throw your platform's standard FileNotFoundException rather than throw PeanutPowersFileNotFoundException. If you really want to throw your own exception, you should probably have it extend the standard FileNotFoundException.
Update: Bloch explains this in Item 60 of Effective Java

It's not. You should create and throw custom exceptions whenever you have an exceptional situation.

It isn't provided they are derived from whatever the standard base exception type is (std::exception in c++, or Exception in python, etc...)
If they _aren't_derived from the normal base type, then other people may not catch them when they are expecting to catch all exceptions - which would be a bad thing.

It's not wrong to create your own exception type. However, before going through creating your own, you should check whether your framework already provides an exception that fits.
From the .Net design guidelines:
Consider throwing existing exceptions
residing in the System namespaces
instead of creating custom exception
types.
Do create and throw custom exceptions
if you have an error condition that
can be programmatically handled in a
different way than any other existing
exceptions. Otherwise, throw one of
the existing exceptions.
Do not create and throw new exceptions
just to have your team's exception.

I believe you might be asking why is it a bad idea to re-throw exceptions.
By "rethrow", I mean catching an exception and than generating a new one and throwing it. This can be problematic, as you could end up consuming the original stack trace and loosing all context of the error.

You should not invent your own type of Exception, unless you have something extra you want to add to the Exception type.
If you want to tell the user of your API that they have provided an invalid argument, you should throw an ArgumentException, but if your library fails because of some library specific reason, that you can't convey in a regular exception, you should roll your own and let it contain the info the developer needs.

To continue Peter's response another case when throwing an exception is not a good idea is if you use throwing exceptions to control the business logic of your program.
As long as the exception you are throwing is derived from a proper object, and conveys just that - exceptional situation, throwing an exception is totally acceptable.
Using throwing exceptions to control business logic in addition to being a bad design pattern has also performance implications - throwing and catching exceptions is rather expensive as compared to branching based on the results returned from the method

There's nothing wrong with creating your own exceptions, which can be tailored to convey exactly the information which is appropriate for your situation. A ConfigFileNotFoundException conveys more information than a FileNotFoundException (which file didn't we find?).
But, by all means, make sure that you catch and handle each and every custom exception inside of your code. When the exception flies to some place outside your module (call it package, call it namespace), those folks out there will not even know that it exists, much less what to do with it. Except for a catch (Throwable t) {/* whut? */}.

To me it seems that the question is to catch inexperienced candidates trying to fake experience. There's nothing wrong about throwing your own exceptions in my opinion, and as you can see to everyone else that answered here.

It's not a bad idea at all. If an exceptional situation arises, an exception should be thrown to handle it, especially if you're designing code that others may use, may receive bad input, etc.
It is a bad idea to use exceptions where they're not absolutely necessary, such as situations that are recoverable by normal checks in code or as part of normal execution, since they do have a lot of overhead associated with them. I imagine that's where you may have gotten the idea that they're a bad idea in general. But for what they're meant to do (flagging an exceptional situation that your code isn't equipped to handle), they're absolutely the best tool.
And if you do create custom exceptions for code others might use, do document what they are and what they mean. That way later users of your code will know that they're possible and what they mean if they arise, and can handle them appropriately.

Related

Is it wrong to thow or catch the Exception Class (every Exception possible)?

I know that a question like this probably depends on what the programmer intends his program to do however at school we were taught to never throw or catch Exception (the class) and rather make sure it throws one of the subclasses more specific to the kind of Runtime error we expect can happen (eg IllegalArgumentException). However, I'm working now and in the 'real world' I see a lot of scenarios in code I work on where the previous programmers threw Exception for everything in a method or catch Exception like that rather than one of its more specific subclasses.
So I'm wondering, Is it ok to throw and catch everything like this, is it bad programming to do so?
My idea is, the way of handle the exceptions should also depend on the type of the application you are creating. For example if you are developing some kind of a framework or a library you should not try to print error messages or log them, you have throw them because it will be responsibility of the other developers who are using your framework/library to handle the exceptions gracefully when they are using your code.
If you are developing some kind of a front end application then you should be more delicate with exception handling. I think it's better you use you own exception classes when possible, because that will help you to pin point the bugs or runtime issues in your application later. When you handle exceptions you should always go from more specific exceptions to general exceptions. And finally you should handle the exceptions of the "Exception" super class so it will make sure that your application doesn't crash, preferably you should have a try-catch block in the main entry point of your application. What ever happens in handling exceptions logging the errors is a good practice when it comes diagnosing the errors later.
It is not wrong to do that but it can make your debugging life very difficult. Many people will catch the exception class and log the Exception.Message. There is not enough detail and, especially if you're working on large systems where you can't always step through the live code etc, it will be a tedious task.
I tend to catch specific exceptions and handle them accordingly BUT I also catch the Exception class to make sure all exceptions are caught going forward (An object might be changed to include more exceptions in future framework versions).
It is bad practice, just as you have learnt.
One major exception to the rule is a top-level exception handler (to catch unhandled exceptions) - the purpose of this would be to log exception so they can be read by a developer later and used to fix the application (and would normally rethrow in order to crash the application - rather than leaving it in an inconsistent state).

Do exceptions break encapsulation?

In the first place, a class or library is created when you do not want to worry about the details of an implementation, but then you need to know the inner workings of the class to properly handle the exceptions it might throw.
Doesn't this break the principle of encapsulation and information hiding ? Or I am totally wrong on this ?
Sure I can have a generic try/catch block to intercept all exceptions, but that is definitely a bad practice.
So how can I come up with good exception handling strategy without knowing the details of each exceptions that might be thrown ?
A well-designed class or library will document what exceptions it throws as part of the interface, perhaps even going so far as to define its own hierarchy of exception classes. For instance, a foo subclass class might throw a "foo persistence exception" if the disk is full, and another subclass would throw one if the network is down. As the caller, you would catch a foo persistence exception because your concern is that data was not persisted. You shouldn't be expected to write code specifically for disk full, network down, disk not present, disk write error, subspace transceiver interference, &c.
It may be the case that you can't do much about many of them.
A class library does not have to throw the same exceptions that its code throws. For expected exceptions that cannot be handled internally, it should probably map to alternate exception types where the "raw" exception would not be readily understood by API consumers. An API consumer should be able to regard expected exceptions as outputs of the API, as one would any other product of usage of the API. Unexpected exceptions, on the other hand, are a whole other ball of wax for both the API developer and consumer...
It's not like that; it's for the end users who are using the end products OR the class "need not to know the inner implementation" but you will know it for sure and hence can hendle the error mechanism accordingly.
BTW, that's the reason any API comes with a good documentation ... so that other developers know at least a bit of it's inner working.
Hopefully this clears the idea.
In the first place, a class or library is created when you do not want
to worry about the details of an implementation, but then you need to
know the inner workings of the class to properly handle the exceptions
it might throw.
Doesn't this break the principle of encapsulation and information
hiding ? Or I am totally wrong on this ?
An exception should thrown when the calee can't fulfill its promises due to some runtime error and can't recover from that state. What exceptions could be thrown must be specified in the interface/documentation. I don't see how this breaks encapsulation. On the other hand, using return codes can't enforce the caller to treat an exceptional error, even by explicitly ignoring it.
Sure I can have a generic try/catch block to intercept all exceptions,
but that is definitely a bad practice.
It is if the designer of the interface you're using didn't clearly specify what exceptions could be thrown and by whom/what_function
So how can I come up with good exception handling strategy without
knowing the details of each exceptions that might be thrown ?
The "details" are in fact the exceptions specifications and that's all you need to know. Again, it should be part of documentation/interface.
Anyway, exceptions should happen rarely, probably thats why someone named them exceptions. If it would happen too often then someone wouldn't name them exceptions anymore but "usuality" or something and the normal, exception-free "code" will become an exception :)
If you're working too much with try/catch bollocks then something is wrong with that code.

Does wrapping everything in try/catch blocks constitute defensive programming?

I have been programming for the last 3 years. When I program, I use to handle all known exceptions and alert the user gracefully. I have seen some code recently which has almost all methods wrapped inside try/catch blocks. The author says it is part of defensive programming. I wonder, is this really defensive programming? Do you recommend putting all your code in try blocks?
My basic rule is : Unless you can fix the problem which caused the exception, do not catch it, let it bubble up to a level where it can be dealt with.
In my experience, 95% of all catch blocks either just ignore the exception (catch {}) or merely log the error and rethrow the exception. The latter might seem like the right thing to do, but in practice, when this is done at every level, you merely end up with your log cluttered with five copies of the same error message. Usually these apps have an "ignore catch" at the top most level (since "we have try/catch at all the lower levels"), resulting in a very slow app with lots of missed exceptions, and an error log that too long for anyone to be willing to look through it.
Extensive use of Try...Catch isn't defensive programming, it's just nailing the corpse in an upright position.
Try...Finally can be used extensively for recovery in the face of unexpected exceptions. Only if you expect an exception and now how to deal with it should you use Try..Catch instead.
Sometimes I see Try..Catch System.Exception, where the catch block just logs the exception and re-throws. There are at least 3 problems with that approach:
Rethrow assumes an unhandled exception, and therefore that the program should terminate because it's in an unknown state. But catch causes the Finally blocks below the Catch block to run. In an undefined situation, the code in these Finally blocks could make the problem worse.
The code in those Finally blocks will change program state. So any logging won't capture the actual program state when the exception was originally thrown. And investigation will be more difficult because the state has changed.
It gives you a miserable debugging experience, because the debugger stops on the rethrow, not the original throw.
No, it's not "defensive programming." Your coworker is trying to rationalize his bad habit by employing a buzzword for a good habit.
What he's doing should be called "sweeping it under the rug." It's like uniformly (void)-ing the error-status return value from method calls.
The term "defensive programming" stands for writing code in such a way that it can recover from error situations or that it avoid the error situation altogether. For example:
private String name;
public void setName(String name) {
}
How do you handle name == null? Do you throw an exception or do you accept it? If it doesn't make sense to have an object without a name, then you should throw an exception. What about name == ""?
But ... later you write an editor. While you set up the UI, you find that there are situations where a user can decide to take the name away or the name can become empty while the user edits it.
Another example:
public boolean isXXX (String s) {
}
Here, the defensive strategy is often to return false when s == null (avoid NPEs when you can).
Or:
public String getName() {
}
A defensive programmer might return "" if name == null to avoid NPEs in calling code.
If you're going to handle random exceptions, handle them in only one place - the very top of the application, for the purposes of:
presenting a friendly message to the user, and
saving the diagnostics.
For everything else, you want the most immediate, location-specific crash possible, so that you catch these things as early as possible - otherwise exception handling becomes a way of hiding sloppy design and code.
In most cases where the exception is predictable, it's possible to test ahead of time, for the condition that the exception handler will catch.
In general, If...Else is much better than Try...Catch.
Catching random exceptions is bad. What then?
Ignore them? Excellent. Let me know how that works for them.
Log them and keep running? I think not.
Throw a different exception as part of crashing? Good luck debugging that.
Catching exceptions for which you can actually do something meaningful is good. These cases are easy to identify and maintain.
Can I just say as an aside here that every time one of my co-workers writes a method signature with "throws Exception" instead of listing the types of exceptions the method really throws, I want to go over and shoot them in the head? The problem is that after a while you've got 14 levels of calls all of which say "throws Exception", so refactoring to make them declare what they really throw is a major exercise.
There is such a thing as "too much" processing, and catching all exceptions kindof defeats the point. Specifically for C++, the catch(...) statement does catch all exceptions but you can't process the contents of that exception because you don't know the type of the exception (and it could be anything).
You should catch the exceptions you can handle fully or partially, rethrowing the partial exceptions. You should not catch any exceptions that you can't handle, because that will just obfuscate errors that may (or rather, will) bite you later on.
I would recommend against this practice. Putting code into try-catch blocks when you know the types of exceptions that can be thrown is one thing. It allows you, as you stated, to gracefully recover and/or alert the user as to the error. However, putting all your code inside such blocks where you don't know what the error is that may occur is using exceptions to control program flow, which is a big no-no.
If you are writing well-structured code, you will know about every exception that can occur, and can catch those specifically. If you don't know how a particular exception can be thrown, then don't catch it, just-in-case. When it happens, you can then figure out the exception, what caused it, and then catch it.
I guess the real answer is "It depends". If try-catch blocks are catching very generic exceptions then I would say it is defensive programming in the same way that never driving out of your neighborhood is defensive driving. A try-catch (imo) should be tailored to specific exceptions.
Again, this is just my opinion, but my concept of defensive programming is that you need fewer/smaller try-catch blocks not more/larger ones. Your code should be doing everything it can to make sure an exception condition can never exist in the first place.
In C++ the one reason to write lots of try/catch blocks is to get a stack trace of where the exception was thrown. What you do is write a try/catch everywhere, and (assuming you aren't at the right spot to deal with the exception) have the catch log some trace info then re-throw the exception. In this way, if an exception bubbles all the way up and causes the program to terminate, you'll have a full stack trace of where it all started to go wrong (if you don't do this, then an unhandled C++ exception will have helpfully unwound the stack and eradicated any possibility of you figuring out where it came from).
I would imagine that in any language with better exception handling (i.e. uncaught exceptions tell you where they came from) you'd want to only catch exceptions if you could do something about them. Otherwise, you're just making your program hard to read.
I've found "try" "catch" blocks to be very useful, especially if anything realtime (such as accessing a database) is used.
Too many? Eye of the beholder.
I've found that copying a log to Word, and searching with "find" -- if the log reader does not have "find" or "search" as part of its included tools -- is a simple but excellent way to slog through verbose logs.
It certainly seems "defensive" in the ordinary sense of the word.
I've found, through experience, to follow whatever your manager, team-leader, or co-worker does. If you're just programming for yourself, use them until the code is "stable" or in debug builds, and then remove them when done.

preconditions and exceptions

Suppose you have a method with some pre and post-conditions.
Is it ok to create an exception class for each pre-condition that is not accomplished?
For example:
Not accomplishing pre1 means throwing a notPre1Exception instance.
Why wouldn't you want to define PreconditionFailedException(string precondition)? Throwing a different exception type for each failed precondition is overkill.
Yes and no.
Yes - Violating a precondition is certainly an appropriate time to throw an exception. Throwing a more specific exception will make catching that specific exception simpler.
No - Declaring a new exception class for every precondition in your program/api seems way overkill. This could result in hundreds or thousands of exceptions eventually. This seems a waste both mentally and computationally.
I would recommend throwing exceptions for precondition violations. I would not, however, recommend defining a new exception for each precondition. Instead, I would recommend creating broader classes of exceptions that cover a specific type of precondition violation, rather than a specific precondition violation. (I would also recommend using existing exceptions where they fit well.)
A failed precondition should throw an AssertException, or something similar. Before invoking a method, it's precondition must hold. If the caller doesn't do this check, it's a bug in the program, or an incorrect use of the method (API).
Only if not accomplishing the pre-conditions would be a rare exceptional occurrence.
Sounds like a useful use of exceptions to me. It certainly allows more fine-grained logging and debugging than just a general 'precondition failed' although you could also have a single 'preconditions failed' exception and put what preconditions have failed into the exception message.
I think it's ok to create a different exception for all your exceptions as long as you plan on using and handling them.
I have found that the better the error/exception handling the easier it is to debug software in the later stages.
For example: If you have a generic excpeiton to handle all bad input then you must look at everything that was passed into the method if there is an error. If you have an excpetion of all the types of bad conditions you will know exaclty where to look.
It looks possible to me, but if you want to continue this way of dealing with preconditions, you'll end up with N exception classes per class method. Looks like an explosive growth of 'non functional' classes.
I always liked code where the 'core' functionality didn't handle violation of preconditions (apart from asserting them - a great help!). This code can then be wrapped in a 'precondition-checker', which does throw exceptions or notifies non-satisfaction otherwise.
As a very very general way to determine if you should ever create a class or not (and an exception is a class), you should determine if there is some code that makes this class unique from all other classes (in this case exceptions).
If not, I'd just set the string in the exception and call it a day. If you are executing code in your exception (perhaps a generic recovery mechanism that can handle multiple situations by calling exception.resolve() or something), then it might be useful.
I realize that exceptions don't always follow this rule, but I think that's more or less because exceptions provided by the language can't have any business logic in them (because they don't know the business--libraries always tend to be full of exceptions to the OO rules)
I think Ben is on target here. What's the point in throwing different exceptions if you're not going to catch them? If you really want to throw a different one I would at least have a common "PreconditionFailedException" base class that they all derive from, and try to organize them into some sort of heirachy so you can catch groups of them. Personlly, I'd not have different ones and just have a common exception you throw with the details of the failure in each one.
No, you should not create a specific exception for each precondition because it will go against the principles of the Design-by-Contract.
The corollaries of implementing pre-conditions is that they should be part of the documentation and that you should provide the necessary methods for the caller to check that all the preconditions are valid. (i.e. if a method execution is relying on the status of an object, the method to check the status should be available to the caller).
So, the caller should be able to check if all prerequisites are met before calling your method.
Implementing specific exceptions for each violated pre-condition would/could encourage the caller to use the try/catch pattern around the method call, what is in contradiction with the philosophy of the Design-by-Contract.
I would say it's okay as long as you make them unchecked exceptions (subclass of RuntimeException in Java). However, in Java it is better to just use assertions.
If you do this, make sure they all inherit from another common custom exception.

Are exceptions really for exceptional errors? [closed]

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.