There is a debate going on at my company regarding exception
conventions. The debate is centered around this...
Should exceptions be used for the not so exceptional error conditions
that arise in an application?
Take for example business level data validation. Imagine something
like validator.validate(myDataObject), which examines the attributes
of myDataObject, and determines if they meet a set of predefined
business requirements. It's clear that such a method would throw an
exception if something such as a lost database connection prevented it
from performing the validation at all. What if the all the validation
could be performed, but the object was "invalid", should it throw an
exception then?
At first I'd be inclined to say no, just return a boolean success flag
or what have you, but isn't that why Java formalized exceptions for in
the first place, because developers tended not to be good about
checking such return conditions.
Imagine a more realistic example of data validation, where you want to
validate all the attributes of myDataObject, and return a more
detailed response as to which attributes were valid, and which were
not (good for validating input from web forms). A boolean success
flag is no good, so we'll need to return some custom errors object.
That doesn't sound like such a big deal, until you start to think of a
large scale system. What if the caller who cares about this errors
object is a few steps up the call stack, now all of a sudden I need to
get this errors object up the stack. This means I've used up my one
return value on all the methods along that stack. That's no good,
especially if pre-existing API in that stack is already using a
meaningful return value. Even if the return values were available, or
say I passed this errors object through as a mutable parameter, I feel
like I've created too much coupling between the different layers by
having this errors object in the all the API's like that.
Now all of a sudden throwing a custom exception like
ValidationFailedException seems like the way to go. That however,
feels to me like we're cheating. "Don't use exceptions for
unexceptional conditions, except when you know that details about the
error needs to be propagated over a few layers", just doesn't sit
right. That's exactly the kind of thing you're not supposed to have
to know when writing OO code. Also, in this validation example, what
would be a good way to add the "details" about the multiple errors
that caused the object to be invalid? If we're going to use
exceptions all over the place, should ValidationFailedException
contain a list of the exceptions that were generated for each invalid
attribute? That seems a little excessive.
My opinion for these kinds of things, is that they can't realistically
be handled on a case by case basis. In a large system, with lots of
different developers, third-party API's, the occasional consultant,
etc., you need a well defined way of doing something as fundamental as
error handling, or you're just going to end up with a big mess
(actually, that is what we have ended up with).
In that light, I'm leaning towards just using exceptions for all
"errors", even for the not so exceptional ones, even if they are
inefficient, even if you have to stick lists of exceptions into
another exception. If anyone else has come up with a different
convention that has worked on a large scale, I'd love to hear about
it?
Regards, Ian
>Take for example business level data validation.
The advantage of exceptions in such situations is that if you have a
hierarchy, the low level guys don't need to be involved in passing the
info up the chain to the decision maker. It just goes there
automatically if they don't handle it. It seems to me this is a much
safer system. It is much less likely someone will totally drop the
ball.
In C people ALL the time ignore return codes from functions. In
contrast, you CAN'T ignore an exception, though you can catch it and
do nothing.
--
Available for tutoring, problem solving or contract
programming for $50 US per hour. The Java glossary is at
http://www.mindprod.com/jgloss.html
or http://64.251.89.39/jagg.html
-
canadian mind products, roedy green
>At first I'd be inclined to say no, just return a boolean success flag
>or what have you
A boolean gives you one bit of information about what went wrong. An
Exception gives you an etire Object dripping with data and
human-readable text.
I'm very much of the opinion that they should. Returning error codes is
a very weak, very old technique that is only rarely appropriate.
> Take for example business level data validation. Imagine something
> like validator.validate(myDataObject), which examines the attributes
> of myDataObject, and determines if they meet a set of predefined
> business requirements. It's clear that such a method would throw an
> exception if something such as a lost database connection prevented it
> from performing the validation at all. What if the all the validation
> could be performed, but the object was "invalid", should it throw an
> exception then?
Let's take an even simpler example: parsing a string into an integer:
public static int Integer.parseInt(String s) throws NumberFormatException;
Note that even for such a simple thing as this, the core API chooses an
exception over a return code. Why? Consider: what would it return if
it didn't choose to use an exception? It would have to either declare some
particular int as being off limits and use that for the error code, or it would
have to return a long and have some magic long outside the bounds of int
indicate errors. Yuck either way. Exceptions are the better way to go.
> At first I'd be inclined to say no, just return a boolean success flag
> or what have you, but isn't that why Java formalized exceptions for in
> the first place, because developers tended not to be good about
> checking such return conditions.
That's actually just one of the reasons. There is also the fact that you can
return more info with an exception, and you can handle them in a more
structured way. The issue of how many levels up the stack the error
handling has to go vanishes completely; it just works. You also get
compiler-enforced documentation of what error conditions are possible.
You get the full benefits of OO in your error data, because your error
data is now an object.
> In that light, I'm leaning towards just using exceptions for all
> "errors", even for the not so exceptional ones, even if they are
> inefficient, even if you have to stick lists of exceptions into
> another exception. If anyone else has come up with a different
> convention that has worked on a large scale, I'd love to hear about
> it?
Go for it!
Marshall
I think that may be the first time that the word "dripping" has been used on
this group ;-)
But seriously, I don't like the idea of a exception in this case. If you
want to return complex info about the validation, then return a
ValidationResult object, or some such. Doesn't have to be a boolean.
I use this technique on my object model. Each class within the model can
implement "Validator" (or maybe "Validatable", can't remember offhand),
which when passed to the persistence mechanism, is checked to make sure it's
valid. Noone else calls it, so noone else is going to drop the ball.
kenny
First, thanks for taking the time to give feedback!
So what about this scenario?... Your persistence mechanism, which
will generate the ValidationResults object upon failed validation, is
a few layers away from your UI, which wants to show the validation
results to the user so they can correct the problems. How do you
reliably, and consistently get the results from A to B? You'd need to
use up all your return values, and there's nothing to say someone
still won't drop the ball (return values can be ignored).
Better yet, what if the object validates, but when you go to persist
it you find it violates some uniqueness constraint in the database.
Imagine the validation rule checks that the lastName property of the
object is not null. This passes, but then uniqueness constraint in
the database prevents the object from being saved because the lastName
already exists. PersistenceManager gets a SQLException, but because
"lastName already exists" is an error based on a defined business rule
(i.e. expected possible failure, and hence not philosophically any
different from the length constraint on the name), it should then
propogate this error as a PersistenceResults object. Now I have to
have a reliable and consistent means of getting a ValidationResults
object, and a PersistenceResults object, accross a few layers from my
PersistenceManager to UI. Now should every method in the stack return
a list of XXXResults objects?
I suppose an alternative to the above scenario would be to map the
SQLException into the ValidationResults object in cases where the
exception was caused by a violation of a business rule. We use the
Oracle JDBC driver. SQLExceptions can have one of many different
detailed error codes. That's a lot of mapping to get right. Then
again, even if I were using exceptions, perhaps I would want
persistence manager to map constraint violations to
ValidationException's anyway, and so the mapping would be unavoidable.
Another problem that could arise from the XXXResults scheme, is that
once you have gotten it from A to B, you're depending on B to properly
interpret the details of the error. For the benefit of this you'd
want the details about the error to be strongly typed. Can you think
of a mecahnism that would accomplish this, and work for any XXXResults
object? With the exception heirarchy scheme that Roedy mentioned,
which is actually what I've been pushing for in the debate at my
company, every error condition is strongly typed by definition of
being a class.
Regards,
Ian
Of course, someone had to research this ;-).
This is the eighth thread in this group to use the word dripping, including
one using it in the subject line "leaking and dripping JVM...". There
were 2 cases talking about something dripping with sarcasm. There was one
instance talking about the way Microsoft goes after something they want with
saliva dripping from their fangs. Another talked about dripping-lazy newbie
questions. And one use in reference to a place, Dripping Sp. in someone's
signature.
This is however the first use of the word dripping in over 2 years.
Just wanted to clear up that little bit of misinformation ;-)
--
Dale King
I think that in this case it has a lot to do with the method name and what
the method is supposed to do. You have chosen to name the method validate.
That is a verb. That implies to me that the method's purpose is to either
make the object valid if it is invalie or at least make sure that the object
is valid. The expectation would be that when that method returns the object
will be valid. It is not expected that the object will be invalid when that
method returns and is therefore an exceptional condition.
But if the method were called isValid then that implies that it is possible
that the object is invalid and that there is no guarantee that the object
will be valid when the method returns. In this case you are only asking if
the object is valid and a boolean result is the proper choice here.
> My opinion for these kinds of things, is that they can't realistically
> be handled on a case by case basis. In a large system, with lots of
> different developers, third-party API's, the occasional consultant,
> etc., you need a well defined way of doing something as fundamental as
> error handling, or you're just going to end up with a big mess
> (actually, that is what we have ended up with).
Handling things on a case-by-case basis is really the only way to handle
them. There are cases where a boolean result is valid and cases where an
exception is the right thing to do. You can certainly come up with
guidelines to help in deciding which way to go, but it still is a
case-by-case decision. The general guideline is that exceptions are for
unexpected things. You don't use exceptions for things that you expect to
happen.
--
Dale King
In theory, I totally agree with you (especially when it comes to the
role of the current context in deteriming what is appropriate). In
practice, I'm not convinced...
In practice, in a large system, for lack of a better mechanism by
which to propogate errors that are defined by business rules, I'm
argueing that exceptions are you're best bet. If we could come up
with a pattern for that missing "good mechanism", I'd be more than
happy to accept that exceptions should only be used in exceptional
conditions.
One distinct reason that I would be happy to use another mechanism, is
because exceptions are based on the termination model of error
handling. I particularly picked data validation for my example
because it is a case that lends itself to the resumption model (or at
least a variation of it), where you want to be smart and compile a
list of errors before ultimately taking exception to the parent
process (I'm assuming that you usually validate in the scope of some
larger operation, and if validation fails, that larger opration should
not proceed).
Regards,
Ian
Of course. At least *I* had the good sense to keep my Googleitis
secret...in this one instance.
;)
Jim S.
Then I don't see where we disagree.
> In practice, in a large system, for lack of a better mechanism by
> which to propogate errors that are defined by business rules, I'm
> argueing that exceptions are you're best bet. If we could come up
> with a pattern for that missing "good mechanism", I'd be more than
> happy to accept that exceptions should only be used in exceptional
> conditions.
I'm not arguing that either is your best bet. I'm simply arguing that which
is best depends on context and primarily on what is expected. If a routine
cannot fulfill what is expected of it, it should throw an exception. The
problem is that what is the expected behavior can only be determined on a
case by case basis. You simply cannot come up with a one-size-fits-all rule
that you should always use exceptions or never use exceptions.
> One distinct reason that I would be happy to use another mechanism, is
> because exceptions are based on the termination model of error
> handling. I particularly picked data validation for my example
> because it is a case that lends itself to the resumption model (or at
> least a variation of it), where you want to be smart and compile a
> list of errors before ultimately taking exception to the parent
> process (I'm assuming that you usually validate in the scope of some
> larger operation, and if validation fails, that larger opration should
> not proceed).
Which contradicts nothing I have said.
--
Dale King
I stand corrected :-)
Both practically and semantically, I don't think "validate" implies
that the method will make the object valid. To validate generally
means to confirm that something is valid:
val搏搞ate Pronunciation Key (vl-dt)
tr.v. val搏搞at搪d, val搏搞at搏ng, val搏搞ates
1. To declare or make legally valid.
2. To mark with an indication of official sanction.
3. To establish the soundness of; corroborate.
However:
> You don't use exceptions for things that you expect to
> happen.
that is correct, and so I think the OP would be wrong to use
exceptions. You could make the argument that Integer.parseInt(String)
uses an exception to convey invalidity, but the OP specifically said
that this is "business rule" validation, not lower-level validation as
of XML or parsing -- thus, I think he would be better off using a
full-featured return object.
Jared
Why not? It is under number 1 of the definition "To make legally valid".
Note that was only one alternative I gave.
> To validate generally
> means to confirm that something is valid:
Which is the other alternative I gave. Either way, to return from that
method it is reasonable to expect that the object in question is either
confirme/declared to be valid or made to be valid.
If you just want a query function to test validity then it should be called
isValid. Ideally you might have both and the validate method calls isValid
and throws and exception if it is not (or tries to make it valid).
> However:
>
> > You don't use exceptions for things that you expect to
> > happen.
>
> that is correct, and so I think the OP would be wrong to use
> exceptions.
Correct but not complete. That is not the only rule governing the choice of
exceptions versus return.
> You could make the argument that Integer.parseInt(String)
> uses an exception to convey invalidity, but the OP specifically said
> that this is "business rule" validation, not lower-level validation as
> of XML or parsing -- thus, I think he would be better off using a
> full-featured return object.
The other rule is that if a method cannot fulfill its contract then it
should throw an exception. That is why parseInt does it. Do we expect it to
fail? Sometimes, but it has more to do with failing to fulfill its contract.
Note I never said that the OP should use exceptions or not. My issue was
more that it depends on the name and purpose of the method. I think having a
validate method not throwing an exception for invalid inputs (that it does
not validate, i.e. make valid) is an incorrect design. I also think an
isValid method that throws an exception is a bad design.
--
Dale King
I would carefully examine why invalidness needs to be propagated up
so far, and if it really does, throw an exception. However,
returning an error object through normal channels might also
be an appropriate response.
I don't see the need for a project wide policy saying either
'use exceptions for business level errors' or the converse.
The specifications should say what happens when bsiness level errors
happend, and for anything beyond that you sholud be depending on the
judgement of your coders, IMHO. It's yet another reason to hire a
few really good people.
--
P. Douglas Reeder Lecturer, Dept. Computer/Info. Science, Ohio State Univ.
ree...@cis.ohio-state.edu http://www.cis.ohio-state.edu/~reeder/reeder.html
GE/S d+ s+:- a C+@$ UH+ P+ L E W++ N+ o? K? w !O M+ V PS+() PE Y+ PGP- t 5+ !X
R>+ tv+ b+++>$ DI+ D- G e+++ h r+>+++ y+>++
I am of the opinion that private and protected functions may return error
codes, but that public (and potentially default) functions should throw
exceptions instead of returning error codes.
The rationale is that throwing an exception requires an object
construction -- that is to be avoided for performance reasons if possible.
Private methods can't be used outside of the class they're defined in, so
the author can ensure that any error code returned is appropriately checked.
Protected methods are usually similar -- unless you're writing a toolkit to
be used by extending the classes in it. But public methods, generally, you
don't have any control over how or when they'll be used. The exception
mechanism ensures that the user of the class will at least think about
potential error conditions -- if only to ignore them.
-- Adam Maass
If find the performance argument unpersuasive. It is making an argument
based on a transient condition: how fast one operation is relative to another
on today's hardware and software. I am more interested in correctness. Performance
can always be tweaked; it can rarely be significantly improved by the kind of
global decision you are proposing.
Marshall
Agreed. I think Java, when used well, and with a high level of
"correctness", is fast enough. If I need to tweak a hot spot here or
there I will, but I'm not going to make a practice out of designing my
API's around whatever minimalizes heap usage. If all I cared about
was speed, I wouldn't be using Java in the first place.
I want a flexible, reliable, maintainable app, with minimal cost of
ownership. Such an app must be built on a robust and maintianable
error handling mechanism. It seems to me that the authors of Java
intended Exceptions to be just such a mechanism. I don't think they
intended to exclude certain "highly foreseeable" errors when they
occur in particular contexts.
It seems obvious that there are many of us users of the language who
find that in practice Exceptions do not lend themselves well to
certain situations. Perhaps it is a fundamental flaw in the design.
Perhaps it is "user error". Perhaps it is a little of both. I'm here
searching not only for the root of the problem, but for a "correct"
solution to it as well.
Regards,
Ian
> It seems obvious that there are many of us users of the language who
> find that in practice Exceptions do not lend themselves well to
> certain situations. Perhaps it is a fundamental flaw in the design.
> Perhaps it is "user error". Perhaps it is a little of both. I'm here
> searching not only for the root of the problem, but for a "correct"
> solution to it as well.
Well, the downside got discussed fairly extensively, I think in the
"most liked, most disliked, little Java features" thread (not its real
name), where the variable scoping and general clutter problems of Java's
try/catch/finally mechanism were roasted thoroughly.
If in general stuff far downstream and out of sight can be expected to
be tossing off exceptions like popcorn, pretty much every method call
needs to be wrapped in a try/catch/finally mechanism.
Now, how much effort are you going to invest in making sure that each
and every one of these wrappers caters explicitly to each and every
possible exception class that can arise from downstream classes?
Probably not very, when it becomes an issue with every call, and so you
are back to "programmers ignoring return values", just with a new spin
on it: almost all exception handling will be for exceptions in general,
not for specific exceptions, and the usual response will be "ignore",
which is pretty counter-productive.
Since you invite a combinatorial explosion of exceptions to handle if
exceptions become your general mechanism for handling problems, this is
probably _not_ a very good idea.
Better is that each class handle its own problems completely, even if
System.err.println(); System.exit(1); is the mechanism; that way calling
code doesn't turn into an unreadable mess, and the two AM call to the
responsible programmer includes a starting place to look for the problem
that is very close to its origin.
Opinions only, of course.
xanthian (based on 41 years programming experience, though; been there,
done that, recommendation: don't!)
--
Posted via Mailgate.ORG Server - http://www.Mailgate.ORG
>I use this technique on my object model. Each class within the model can
>implement "Validator" (or maybe "Validatable", can't remember offhand),
>which when passed to the persistence mechanism, is checked to make sure it's
>valid. Noone else calls it, so noone else is going to drop the ball.
THe problem is all has to be co-ordinated every layer has to
understand it, be able to deal with problems from below and also its
own, merging.
Exceptions handles it all very neatly. If your middle layer is not
prepared to deal with it, it basically ignores it and leaves it up to
a higher level to deal with.
>But seriously, I don't like the idea of a exception in this case. If you
>want to return complex info about the validation, then return a
>ValidationResult object, or some such. Doesn't have to be a boolean
If you do that you have lost the ability to return any REAL data. You
have wasted your only return object on status info.
I'm not sure I understand your meaning here. If my validate() method
returns an object, I can put as much or as little data in that object as I
wish. Doesn't have to limit itself to status codes. Anything you can out
into an exception, you can put into a return object.
kenny
Hmm. I have a cohesive object graph, and a single point of entry into my
persistence layer. So the isValid() methods are only present in the object
model, and are only invoked from the persistence layer facde. Where does
the problem occur?
> Exceptions handles it all very neatly. If your middle layer is not
> prepared to deal with it, it basically ignores it and leaves it up to
> a higher level to deal with.
My persistence facade examines the result of isValid() on the persistable
object, and throws an exception if it doesn't like the result. The effect
is the same as throwing the exception directly out of the persistable
object.
My contention is that it is not the job of the persistable object to throw
this exception, since it doesn't know the contect in which this exception
would be thrown. For example, if we have a presentation layer component,
which keeps sending the user back to the same screen until they enter valid
data, then I'd say an exception is not appropriate, since this is standard
behaviour for the presentation layer. In contrast, if an invalid object is
sent to the persistence layer, which is very definately an exception
condition, then an exception should be thrown. But the persistable object
doesn't have anough knowledge about its context to make that decision.
Just my $0.02, as always,
kenny
>I'm not sure I understand your meaning here. If my validate() method
>returns an object, I can put as much or as little data in that object as I
>wish. Doesn't have to limit itself to status codes. Anything you can out
>into an exception, you can put into a return object.
In theory yes, in practice no. A method has to deal with whatever it
wants to return as data, its status, and lower level status. You
would need a return-type class for every method!! :-).
As the program evolves that return-type object has to keep changing to
reflect the new strange combinations of conditions it must track.
A boolean status return is great when the immediate layer above is
doing going to deal with the success/fail. boolean isValid() makes
perfect sense.
However, when exceptions are PERIPHERAL to delivering a result, and it
is not clear who will deal with the exception. then exceptions are
much tidier and more foolproof.
I repeat. Think of how much C code you have seen that ignores return
codes either deliberately or inadvertently. The compiler does not
care. In contrast, you can't close your eyes and TOTALLY ignore an
exception.
I see your point, but a technique I have used in the past, although not for
this specific purpose, is to use a class which wraps a DOM-like object
(usually a JDOM Element). This allows you to add arbitrarily complex data
to the object. As long as these objects are not pivotal to the design's
integrity, it makes a good tool.
> However, when exceptions are PERIPHERAL to delivering a result, and it
> is not clear who will deal with the exception. then exceptions are
> much tidier and more foolproof.
Agreed. See my other post about the appropriateness of throwing exceptions
in this case.
> I repeat. Think of how much C code you have seen that ignores return
> codes either deliberately or inadvertently. The compiler does not
> care. In contrast, you can't close your eyes and TOTALLY ignore an
> exception.
I'll conecde that if the method is to be called at numerous places
throughout your application, then an exception may be a more generic and
safer solution. Otherwise, I'd still most likely use a return status.
kenny
I am currently working on a large C project (with about 20 developers) and
we just recently had a major effort to go back through and clean up all the
return codes that were being ignored. If they can be ignored, they will be
ignored.
--
Dale King
[snip]
But what if what is expected of the routine is to detect an error
condition(s)? Just because a routine fulfills it's contract, doesn't
necessarily mean it did so without encoutering or creating errors that
need to be be dealt with by a higher context. An error in you're
program is an error in you're program, be it low-level, high-level,
system-rule-oriented, or business-rule-oriented. Why should a certain
error condition be modeled as an exception in one context, but not in
another? Why would Gosling, et al sit down and say, "Okay, error
handling has traditionally been a problem in C++ and other languages.
Let's try to solve this problem in Java, but only for certain
contexts. The same errors in other contexts will have to be handled
the old problematic ways of return codes and what not."? I'm sure
none of us believe that was the original intent.
Regards,
Ian
But that is not enough information to determine its contract. The contract
of isValid is clearly to simply report whether something is valid. The
contract of validate implies to me that when the method returns the object
will be valid.
> An error in you're
> program is an error in you're program, be it low-level, high-level,
> system-rule-oriented, or business-rule-oriented. Why should a certain
> error condition be modeled as an exception in one context, but not in
> another?
Who said it was an error condition?
> Why would Gosling, et al sit down and say, "Okay, error
> handling has traditionally been a problem in C++ and other languages.
> Let's try to solve this problem in Java, but only for certain
> contexts. The same errors in other contexts will have to be handled
> the old problematic ways of return codes and what not."? I'm sure
> none of us believe that was the original intent.
You are greatly expanding the word "error". Errors should be exceptions. The
question is whether something is truly an error.
--
Dale King
Let me take the extremist position (which is not just a mask I'm putting
on; I really believe what I'm saying).
Exception handling is a form of conditional control flow. It has several
very big advantages:
1. It allows attachment of an arbitrary notation, with arbitrary amounts
of structure and data, to the choices it makes.
2. It is unobtrusive in ways that other control flow statements are not;
it doesn't require any code whatsoever to be written at individual branch
points.
It also has several big disadvantages over other forms of conditional
control flow in Java:
1. The branch points themselves are less obvious.
2. It's far more complex than if or switch statements.
(Note: there are, I'm sure, infinitely many other smaller advantages and
disadvantages that could be listed... I'll stop here.)
The task is not to pick a particular piece of vocabulary and hold your
problem up against that word as a measuring stick, but rather to
determine how your problem interacts with the advantages and
disadvantages listed above. If the problem can benefit the advantages
(even just one of the advantages, if it's good enough), and the
disadvantages don't cause too many problems to outweight that advantage,
then exception handling is a valid choice. This is true even if the
situation at hand has nothing to do with error conditions.
Example: Say you're writing a complex recursive search algorithm, and you
want to immediately abort the whole thing and return when you find the
correct answer. Is it a valid choice to throw an exception to
communicate the answer to the top-level routine to be returned to the
caller? I'd say "maybe, depending on how clumsy the other solutions
are". I get the feeling you'd answer "no" on principle. If the
exception infrastructure helps the situation and makes the code easier to
read as a whole, I don't see any big problem.
Chris Smith
[snip]
> > But what if what is expected of the routine is to detect an error
In my last post I was trying to get away from the validation examples
and just speak in general terms, so we wouldn't get hung up on
vocabulary interpretation. Originally I used validate(...) in
the same way you'd like to use isValid(...). I understand the
distinction you've made between the two, and can agree on the dialect
you've chosen, but just to have a fresh prospective let me use a
couple different examples. Hopefully these examples will alleviate us
from the debate over what is or isn't an "error", and let us focus on
the different ways that errors can be modeled and dealt with.
Case 1:
/**
* Checks for an error condition.
*
* @return true if the condition exists, false otherwise
* @throws CouldNotCheckException if the method could not
* make the check.
*/
public boolean checkForErrorCondition()
throws CouldNotCheckException
Case 2:
/**
* Checks for an error condition.
* Returns silently if no error is detected.
*
* @throws ErrorFoundException if the error condition is found.
* @throws CouldNotCheckException if the method could not make
* the check.
*/
public void checkForErrorCondtion(...)
throws ErrorFoundException, CouldNotCheckException
The purpose of each of these methods is to identify an error in the
system. In case #1, a return code is used to signify whether or not
an error was detected. Case #2 returns silently if there is no error,
or throws an exception if an error is found. Each throws an exception
if it couldn't even determine whether or not there was an error
condition.
Some might say that case 1 is the correct way to use exceptions.
Since the method's purpose is to detect an error condition, finding an
error condition is a perfectly reasonable and foreseeable outcome,
hence an exception should not be used in this context. It's not like
you asked this method to give you the error (e.g.
getErrorCondtition()), you just asked it if there was one, yes or no.
I feel that case #2 is correct. I feel that if you want a robust
system, you need to handle errors (expected or unexpected) in a robust
manner. I see that someone could call the method in case #1, the
method could find an error condition in my system, but the caller
could make the historic mistake of ignoring the return code. Now I
have a known but un-addressed error condition in my system, one that I
would have been much less likely to have if I had gone with case #2.
This is why I feel we can't let things such as the context of a
particular method (which is open for misinterpretation-interpretation
simply based
on the meanings associated with the name that was chosen for the
method) be the deciding factor as to how we model and handle errors in
our systems.
Now, back to the debate over what is an "error"? Does you're boolean
success flag start off equal to true, or false? Mine starts off false
(not that I'd tend to use one in the first place, incase you didn't
catch the sarcasm and irony there). ;) In the interest of a robust
system, I'll be glad to take the pessimistic, defensive approach and
consider any fault in my system an error. Invalid data,,, error.
Couldn't find something,,, error. If the caller knows how to handle
the problem, then by all means they can catch the exception and deal
with it.
Regards,
Ian
Which agrees with my point all along. I was arguing against the position
that one should declare that everything will use exceptions or everything
will use return codes. It all depends on context.
--
Dale King