Error Handling

R

Rhino

I'm trying to figure out some "best practices" for error handling.

Our various recent discussions have convinced me that many error situations
should probably not be handled via Exceptions, particularly things like
input errors on GUIs. I know there is a school of thought that says
exceptions are a reasonable approach to some input errors but that seems to
be the minority opinion; most people prefer other ways.

I'm trying to understand what the best approach is for a few different
situations.

1. User input errors in a GUI.

The user has a form or panel in front of him and is asked to enter his date
of birth; despite help screens and labels advising him that the format is
year-month-day separated by dashes, e.g. 2010-05-28, he enters this
information incorrectly, e.g. 05/28/10. The code that validates the input on
the form detects this error. How should the user be notified of this error?
I'm picturing a utility class being invoked by the GUI to validate the date
since this kind of validation is going to be very routine. Obviously, the
utility method is going to format an error message that tells the user what
is wrong (in the appropriate language) but then what?

I've seen, written, or used programs where that message would be displayed
back on the input panel, typically in a position that the builders of the
system think is going to be the most readily seen, like just above the input
panel or just below it. Often, you would flag the particular input field
that is in error. This feels rather 'old school' at this point but the basic
design is tried and true and it worked pretty well.

I've seen, written, or used programs where an error message popped up on in
its own window, advising the user what the error is. (Of course, this
approach needs a bit of care since you want to make sure that the message
isn't modal so that the user can see the message but also the input field so
that he can grasp the error. And you want the error window to be movable so
that it isn't frozen in one position and covering the input field that is in
error.)

Which of these do very experienced Java developers prefer? Or is there a
different approach that is better than these? I'm mostly concerning with
Java applications today, as opposed to applets or servlets, but I write all
of those types so I'm interested in the best way of error handling for all
types of Java programs.

And what would the code in the method that detects the error look like? I'm
picturing if statements that test the input and then format a message if an
error is seen. But what actually gets returned to the calling class?
Presumably, the method that edits the date was going to return a boolean
indicating if the data is good or not but how does the error message get
back to the caller? (At one point, I was writing edits like this to return
an array of Objects; the array always started with the boolean that says if
the data was good or not and, if the data was bad, the second Object would
be an error message. If the data was good though, only the boolean was
returned. Is that a good or bad design? It _felt_ wrong and forced the
calling class to parse the array but it worked okay.)

Also, am I correct in thinking that errors of the kind I am describing
should not be logged, even at a very detailed level, since the log should
only be for serious things that would involve a system administrator? (I'm
tempted to argue that the log _could_ be a place where user errors get
recorded so that people managing the users know which of their people are
having a lot of errors so that remedial training might be provided but I
suspect you will persuade me that that kind of requirement should be handled
differently.)


2. Bad input errors from a process which doesn't use a GUI.

One of my projects writes resumes to files for eventual placement on a
website. The classes that write the resumes use various utility classes to
write the resume files but there is no GUI involved. The classes make
frequent use of various utility classes that help with issues like
formatting. My project classes invoke the methods in the utility classes and
sometimes I make mistakes in invoking the method in the utility class.
Typically, it's because I've made a typo or forgotten the range of
acceptable values for a parameter to the method. So, let's say I'm going to
invoke a method that causes text to wrap on the page of a document and I've
specified one of the parameters incorrectly, perhaps the width in characters
of the available space. When I run my resume-generating class, that method
invocation is going to fail because the wrapping method is going to detect
that I've given it invalid input but there is not going to be a GUI on which
to display the message for that error. So how should that be handled?

Frankly, I feel a little odd in asking about this type of error because they
are essentially programming errors, not runtime-type errors. Basically, the
user of the class didn't understand the method that was being invoked well
enough to avoid coding unreasonable parameters in the invocation. But these
kinds of things do happen so maybe it's not ridiculous to mention them. Or
should I just assume that test cases will find these errors so that they can
be rectified during development and that it's not necessary to design for
this kind of situation.

Again, I'm assuming that errors like this shouldn't be logged.

3. Serious errors causes by programmer error.

Consider this example. Let's say that I have a method which tries to obtain
a resource bundle given input parameters like the "base name" of the
resource bundle. This base name is simply a String typed by a programmer but
the programmer recently made some coding changes and misspelled the base
name during those changes. This is rather similar to the second type of
error I just raised but this time, the consequences of the problem are a lot
more severe. Without a correctly-spelled base name, much of the information
needed by the classes won't be found and the classes are basically dead in
the water. But it is still just a programmer error: somebody mistyped the
base name.

Should there be any specific error handling within the method that looks for
the resource bundle or is it reasonable to code it as if it will inevitably
work and then assume that unit testing will catch it if the base name is
misspelled?

Should this type of error be logged? If this error will prevent the rest of
the classes' work from proceeding satisfactorily, do I just System.exit()
with a message on the console or are there better things to do?

4. Really bad errors not caused by the programmer.

A routine method in a class somewhere tries to find a file on a server
somewhere and the file is inaccessible because someone messed with file
permissions. Or a method tries to access information on a server and the
server is down for some reason. Or any of umpteen other things beyond the
control of the programmer takes place but makes it impossible for the class
to carry on.

I assume that ALL such situations should be logged. (Some of them will
surely be so obvious that the logging is redundant - every resource you're
trying to get from your server in Chile is unavailable and CNN just
announced an earthquake close to the server's location - but many are likely
to be more subtle and would not automatically be noticed by system
administrators with a nudge from the logs.)

What notifications should users receive in such cases? What notifications
should batch programs make in those cases?

Overall, I'm trying to figure out what situations need error messages, who
should see those messages and where they should be written. (Also, what
situations would call for me to write to the console? Who would normally see
the console output from a production application?)

Sorry for asking yet another "big" question but I need this kind of
knowledge to make my code more acceptable than it is....
 
E

Eric Sosman

I'm trying to figure out some "best practices" for error handling.

Our various recent discussions have convinced me that many error situations
should probably not be handled via Exceptions, particularly things like
input errors on GUIs. I know there is a school of thought that says
exceptions are a reasonable approach to some input errors but that seems to
be the minority opinion; most people prefer other ways.

Don't conflate the program's mechanisms for detecting and
handling errors with the way they are presented to a user. It
doesn't matter to the user whether the original detection of the
error reported it by throwing, or by returning null, or by some
other means: The user just needs to know that the program couldn't
do what was asked of it, plus whatever information might be
helpful in figuring out what to do next.
1. User input errors in a GUI.
[...]
And what would the code in the method that detects the error look like? I'm
picturing if statements that test the input and then format a message if an
error is seen. But what actually gets returned to the calling class?
Presumably, the method that edits the date was going to return a boolean
indicating if the data is good or not but how does the error message get
back to the caller? (At one point, I was writing edits like this to return
an array of Objects; the array always started with the boolean that says if
the data was good or not and, if the data was bad, the second Object would
be an error message. If the data was good though, only the boolean was
returned. Is that a good or bad design? It _felt_ wrong and forced the
calling class to parse the array but it worked okay.)

An array of Object[] is unattractive, forcing the caller through
ugly downcasts and so on. Even BigInteger.divideAndRemainder() is
pretty hokey, IMHO. If you want to return multiple things, it's
often better to write a simple "holder" class to contain them.

Another approach is to pass a "status" object to the method, which
the method can mutate to pass back information about how things went.
See, for example, ParsePosition.

One of the attractions of using exceptions is that they can carry
information of types unrelated to what the code might otherwise compute.

Combined strategies can also be used, along the lines of

Value getValue(String input, Status status) {
...
if (all_went_well) {
status.setValid(true);
return convertedValue;
}
else {
status.setValid(false);
status.setMessage("No comprendo");
return null;
}
}

Value getValue(String input) throws BadValueException {
Status status = new Status();
Value value = getValue(input, status);
if (status.isValid())
return value;
throw new BadValueException(status.getMessage());
}
Also, am I correct in thinking that errors of the kind I am describing
should not be logged, even at a very detailed level, since the log should
only be for serious things that would involve a system administrator? (I'm
tempted to argue that the log _could_ be a place where user errors get
recorded so that people managing the users know which of their people are
having a lot of errors so that remedial training might be provided but I
suspect you will persuade me that that kind of requirement should be handled
differently.)

Most input errors aren't worth logging. Some are: For example,
if the error message is "Invalid username and/or password", someone
might be interested in the fact that seven thousand of them have
been generated in the last two minutes, and might want to find out
something about where they're coming from ...

(Incidentally, when logging authentication failures you might
want to omit the failed username/password combination. Someone
might guess that a failed password is a simple typo for the real
password, and find the latter with a very brief brute-force search.
Also, people occasionally get "out of sync" and enter usernames and
passwords in the wrong boxes, so logging just the username can also
wind up logging some passwords. If you must log them for forensic
reasons, at least encrypt those parts of the log against casual
snooping.)
 
R

Rhino

Eric Sosman said:
Don't conflate the program's mechanisms for detecting and
handling errors with the way they are presented to a user. It
doesn't matter to the user whether the original detection of the
error reported it by throwing, or by returning null, or by some
other means: The user just needs to know that the program couldn't
do what was asked of it, plus whatever information might be
helpful in figuring out what to do next.
Sure. Sorry if my remarks made it look like I didn't make any distinction
between the two.
1. User input errors in a GUI.
[...]
And what would the code in the method that detects the error look like?
I'm
picturing if statements that test the input and then format a message if
an
error is seen. But what actually gets returned to the calling class?
Presumably, the method that edits the date was going to return a boolean
indicating if the data is good or not but how does the error message get
back to the caller? (At one point, I was writing edits like this to
return
an array of Objects; the array always started with the boolean that says
if
the data was good or not and, if the data was bad, the second Object
would
be an error message. If the data was good though, only the boolean was
returned. Is that a good or bad design? It _felt_ wrong and forced the
calling class to parse the array but it worked okay.)

An array of Object[] is unattractive, forcing the caller through
ugly downcasts and so on. Even BigInteger.divideAndRemainder() is
pretty hokey, IMHO. If you want to return multiple things, it's
often better to write a simple "holder" class to contain them.
Fair enough. The holder class could have two values in it, the boolean and
the error message, just like Object array, but I'd use getters from the
holder class to find out what value is in each.
That would be a simple example of what you mean?
Another approach is to pass a "status" object to the method, which
the method can mutate to pass back information about how things went.
See, for example, ParsePosition.
ParsePosition itself looks simple enough, at least in the Javadoc, but I'll
have to look at the source for several Java classes to see how it updates
itself and how the final result gets passed back to the caller....
One of the attractions of using exceptions is that they can carry
information of types unrelated to what the code might otherwise compute.
I'm not actually that ooposed to using exceptions but I'd like to know the
other options too. It's hard to make an informed choice if you don't know
the other options ;-)
Combined strategies can also be used, along the lines of

Value getValue(String input, Status status) {
...
if (all_went_well) {
status.setValid(true);
return convertedValue;
}
else {
status.setValid(false);
status.setMessage("No comprendo");
return null;
}
}

Value getValue(String input) throws BadValueException {
Status status = new Status();
Value value = getValue(input, status);
if (status.isValid())
return value;
throw new BadValueException(status.getMessage());
}


Most input errors aren't worth logging. Some are: For example,
if the error message is "Invalid username and/or password", someone
might be interested in the fact that seven thousand of them have
been generated in the last two minutes, and might want to find out
something about where they're coming from ...

(Incidentally, when logging authentication failures you might
want to omit the failed username/password combination. Someone
might guess that a failed password is a simple typo for the real
password, and find the latter with a very brief brute-force search.
Also, people occasionally get "out of sync" and enter usernames and
passwords in the wrong boxes, so logging just the username can also
wind up logging some passwords. If you must log them for forensic
reasons, at least encrypt those parts of the log against casual
snooping.)
Sound advice, as always. Thanks Eric!
 
D

Daniel Pitts

Thank you. Money is tight right now so I won't be able to get that book
right away but I'll look at buying it when I have a bit more disposable
income....
You might try your local library or book store. Near where I live,
Borders is a good place to pick up a book and read it before buying it.

Some might say this is a dubious activity, however I buy plenty of books
and also patronize the coffee shop frequently.
 
J

Jeff Higgins

You might try your local library or book store. Near where I live,
Borders is a good place to pick up a book and read it before buying it.

Some might say this is a dubious activity, however I buy plenty of books
and also patronize the coffee shop frequently.

My local public library is very good about inter-library loans. If the
book can be obtained from within the state there is no charge for postage.
Unfortunately I've lived in regions where support for ILL was not so good.
 
J

Jeff Higgins

1. User input errors in a GUI.

The user has a form or panel in front of him and is asked to enter his date
of birth; despite help screens and labels advising him that the format is
year-month-day separated by dashes, e.g. 2010-05-28, he enters this
information incorrectly, e.g. 05/28/10. The code that validates the input on
the form detects this error. How should the user be notified of this error?
I'm picturing a utility class being invoked by the GUI to validate the date
since this kind of validation is going to be very routine. Obviously, the
utility method is going to format an error message that tells the user what
is wrong (in the appropriate language) but then what?

<http://java.sun.com/javase/6/docs/api/javax/swing/JFormattedTextField.html>
<http://java.sun.com/docs/books/tutorial/uiswing/components/formattedtextfield.html>
 
A

Arved Sandstrom

Rhino said:
I'm trying to figure out some "best practices" for error handling.

Our various recent discussions have convinced me that many error situations
should probably not be handled via Exceptions, particularly things like
input errors on GUIs. I know there is a school of thought that says
exceptions are a reasonable approach to some input errors but that seems to
be the minority opinion; most people prefer other ways.

I'm trying to understand what the best approach is for a few different
situations.

1. User input errors in a GUI.

The user has a form or panel in front of him and is asked to enter his date
of birth; despite help screens and labels advising him that the format is
year-month-day separated by dashes, e.g. 2010-05-28, he enters this
information incorrectly, e.g. 05/28/10. The code that validates the input on
the form detects this error. How should the user be notified of this error?
I'm picturing a utility class being invoked by the GUI to validate the date
since this kind of validation is going to be very routine. Obviously, the
utility method is going to format an error message that tells the user what
is wrong (in the appropriate language) but then what?

Be aware (you may already be) that if the GUI is a web application GUI,
that the odds are pretty good that much of the validation will be
handled by a framework. For example, the scenario you posit is indeed so
routine that built-in mechanisms in many web frameworks will handle this
without any Java coding on your part being required at all...you just
have to designate in web pages which input elements need this kind of
date format conversion.
I've seen, written, or used programs where that message would be displayed
back on the input panel, typically in a position that the builders of the
system think is going to be the most readily seen, like just above the input
panel or just below it. Often, you would flag the particular input field
that is in error. This feels rather 'old school' at this point but the basic
design is tried and true and it worked pretty well.

This "old school" approach is the one that works best, IMHO. You have
several different types of input problems:

1. A single input element - usually the error message is displayed right
by the offending input element;

2. A group of input elements - you have a bit more freedom as to where
to place the error message; using the page top as a standard location
for more general error messages is not uncommon.
I've seen, written, or used programs where an error message popped up on in
its own window, advising the user what the error is. (Of course, this
approach needs a bit of care since you want to make sure that the message
isn't modal so that the user can see the message but also the input field so
that he can grasp the error. And you want the error window to be movable so
that it isn't frozen in one position and covering the input field that is in
error.)

Which of these do very experienced Java developers prefer? Or is there a
different approach that is better than these? I'm mostly concerning with
Java applications today, as opposed to applets or servlets, but I write all
of those types so I'm interested in the best way of error handling for all
types of Java programs.

I don't myself use dialogs/popups for errors; I use these for normal
workflow and only where it makes sense. I keep errors to same page
messages or standard error pages.
And what would the code in the method that detects the error look like? I'm
picturing if statements that test the input and then format a message if an
error is seen. But what actually gets returned to the calling class?
Presumably, the method that edits the date was going to return a boolean
indicating if the data is good or not but how does the error message get
back to the caller? (At one point, I was writing edits like this to return
an array of Objects; the array always started with the boolean that says if
the data was good or not and, if the data was bad, the second Object would
be an error message. If the data was good though, only the boolean was
returned. Is that a good or bad design? It _felt_ wrong and forced the
calling class to parse the array but it worked okay.)

See above - in a web application environment your framework will handle
these low level details. Often you won't need any code at all. Even
where you do (for more elaborate validation possibly involving a number
of inputs plus the business context) you often don't have to do more
than supply just a validation method, and possibly a custom message in a
properties file, and hook it into the framework.
Also, am I correct in thinking that errors of the kind I am describing
should not be logged, even at a very detailed level, since the log should
only be for serious things that would involve a system administrator? (I'm
tempted to argue that the log _could_ be a place where user errors get
recorded so that people managing the users know which of their people are
having a lot of errors so that remedial training might be provided but I
suspect you will persuade me that that kind of requirement should be handled
differently.)
[ SNIP ]
I wouldn't myself log a user input validation error, since there is no
error from the application standpoint.

AHS
 
R

Rhino

Daniel Pitts said:
You might try your local library or book store. Near where I live, Borders
is a good place to pick up a book and read it before buying it.

Some might say this is a dubious activity, however I buy plenty of books
and also patronize the coffee shop frequently.

That would be a better strategy for a situation where I just want to get one
or two details and could write them down or memorize them while "browsing".
But the description makes it look like there's lot of good stuff inside, far
more than I could reasonably memorize or summarize even if I spent a couple
of hours browsing.

Thanks for the suggestion though! It would be good in other situations :)
 
R

Rhino

Jeff Higgins said:
My local public library is very good about inter-library loans. If the
book can be obtained from within the state there is no charge for postage.
Unfortunately I've lived in regions where support for ILL was not so good.

We have ILL loans at our local library. I don't recall ever having had one
but I know they are available. I've heard it can take many weeks for the
book to materialize though so that doesn't do me much good today ;-) And
I've still got the challenge of either memorizing or summarizing large
quantities of information before the book has to be returned. I've got more
time to do it but still.... If the book is as good as the reviews look, I
think I need to buy it.
 
R

Rhino

Be aware (you may already be) that if the GUI is a web application GUI,
that the odds are pretty good that much of the validation will be handled
by a framework. For example, the scenario you posit is indeed so routine
that built-in mechanisms in many web frameworks will handle this without
any Java coding on your part being required at all...you just have to
designate in web pages which input elements need this kind of date format
conversion.
I've seen, written, or used programs where that message would be
displayed back on the input panel, typically in a position that the
builders of the system think is going to be the most readily seen, like
just above the input panel or just below it. Often, you would flag the
particular input field that is in error. This feels rather 'old school'
at this point but the basic design is tried and true and it worked pretty
well.

This "old school" approach is the one that works best, IMHO. You have
several different types of input problems:

1. A single input element - usually the error message is displayed right
by the offending input element;

2. A group of input elements - you have a bit more freedom as to where to
place the error message; using the page top as a standard location for
more general error messages is not uncommon.
I've seen, written, or used programs where an error message popped up on
in its own window, advising the user what the error is. (Of course, this
approach needs a bit of care since you want to make sure that the message
isn't modal so that the user can see the message but also the input field
so that he can grasp the error. And you want the error window to be
movable so that it isn't frozen in one position and covering the input
field that is in error.)

Which of these do very experienced Java developers prefer? Or is there a
different approach that is better than these? I'm mostly concerning with
Java applications today, as opposed to applets or servlets, but I write
all of those types so I'm interested in the best way of error handling
for all types of Java programs.

I don't myself use dialogs/popups for errors; I use these for normal
workflow and only where it makes sense. I keep errors to same page
messages or standard error pages.
And what would the code in the method that detects the error look like?
I'm picturing if statements that test the input and then format a message
if an error is seen. But what actually gets returned to the calling
class? Presumably, the method that edits the date was going to return a
boolean indicating if the data is good or not but how does the error
message get back to the caller? (At one point, I was writing edits like
this to return an array of Objects; the array always started with the
boolean that says if the data was good or not and, if the data was bad,
the second Object would be an error message. If the data was good though,
only the boolean was returned. Is that a good or bad design? It _felt_
wrong and forced the calling class to parse the array but it worked
okay.)

See above - in a web application environment your framework will handle
these low level details. Often you won't need any code at all. Even where
you do (for more elaborate validation possibly involving a number of
inputs plus the business context) you often don't have to do more than
supply just a validation method, and possibly a custom message in a
properties file, and hook it into the framework.
Also, am I correct in thinking that errors of the kind I am describing
should not be logged, even at a very detailed level, since the log should
only be for serious things that would involve a system administrator?
(I'm tempted to argue that the log _could_ be a place where user errors
get recorded so that people managing the users know which of their people
are having a lot of errors so that remedial training might be provided
but I suspect you will persuade me that that kind of requirement should
be handled differently.)
[ SNIP ]
I wouldn't myself log a user input validation error, since there is no
error from the application standpoint.
Thanks for talking about these errors from the perspective of frameworks. I
didn't want to lose sight of that whole class of applications, even if it is
not my focus today! I haven't used any frameworks per se but I have heard
some intriguing things about them and definitely want to work with them when
I get a chance....
 
L

Lew

That would be a better strategy for a situation where I just want to get one
or two details and could write them down or memorize them while "browsing".
But the description makes it look like there's lot of good stuff inside, far
more than I could reasonably memorize or summarize even if I spent a couple
of hours browsing.

You just will come up with any excuse not to read, won't you?

First it was that you can't afford it. Then people (repeatedly) suggest a way
to do it for free and you now claim that there isn't enough time in those
situations to read. Oh, and what was your excuse not to use a library?
Thanks for the suggestion though! It would be good in other situations :)

Yeah, situations that involve a programmer actually willing to do what it
takes to learn their craft. Except for those situations, I guess the
suggestions are pretty useless.
 
M

markspace

Rhino said:
Our various recent discussions have convinced me that many error situations
should probably not be handled via Exceptions, particularly things like
input errors on GUIs. I know there is a school of thought that says


In general, log everything, and throw on everything. This contradicts
some advice you've got already on this thread. I'll try to justify my
reasons.

exceptions are a reasonable approach to some input errors but that seems to
be the minority opinion; most people prefer other ways.


As a special case, when validating an input value it isn't really
"wrong" for the value to be incorrect, so it's OK to return true or
false and not throw an exception. If you receive a bad value where you
weren't expecting it, throw an exception.

I've seen, written, or used programs where that message would be displayed
back on the input panel, typically in a position that the builders of the
system think is going to be the most readily seen, like just above the input


As others have mentioned, I like this one best too. Acknowledging a
pop-up is annoying and takes a "user gesture." Too many user gestures
and a program is just plain bothersome and hard to use.

I'm mostly concerning with
Java applications today, as opposed to applets or servlets, but I write all
of those types so I'm interested in the best way of error handling for all
types of Java programs.


I happen to be dealing with a JEE app that was written by someone who
appears to be a decent but inexperienced coder. All code captures any
exception, prints a stack trace, and then just returns. This results in
a hung app if something important fails, and it happens that the
database is unstable right now. But the servlet can't know that the
database has gone off-line, because there's no exception, so the servlet
just calls the next method and everything hangs.

Throwing exceptions instead of printing a message and then swallowing
them would have resulted an app that was easier to test, rather than one
that just timed out but gave no indication to the tester when or why.

Throw all exceptions, until you get to the user's level, then do
something to make a nice error result. In this case the servlet should
have caught the error, logged it, and then dispatch a nice error page
instead of just hanging forever.

And what would the code in the method that detects the error look like? I'm
picturing if statements that test the input and then format a message if an
error is seen.


Throw an exception, and format its message for the programmer. Include
all relevant arguments and any relevant internal objects too, even if
private.

For example, on an array index out of range exception, return the index
value the programmer passed in, so the programmer can see what they did,
and the size of the array that was exceeded, so the programmer can see
what they should have done.

Let the higher level code decide what message the user should see.

Also, am I correct in thinking that errors of the kind I am describing
should not be logged, even at a very detailed level, since the log should
only be for serious things that would involve a system administrator?


I log everything. When I'm writing code, I'm normally writing the unit
test at the same time. I crank up the log level to FINER or ALL, put
everything I need to see in log messages, and add a ConsoleHandler so I
can see it easily. Then when it all seems to work, I reduce the log
level but I leave that logging still there. That way all the work I
went through when deciding what to log is not lost, and it's all still
there if I or someone else should need it again.

Don't ignore optimization: Use "isLoggable(Level)" everywhere and
minimize the places where you have to call it, but don't stint either.
Your time is more valuable that the CPU's.

This is the true value of "log everything," imo. Having a routine
that's already well instrumented when you need to go back to it and
debug something is a great time-saver in the long run.

Typically, it's because I've made a typo or forgotten the range of
acceptable values for a parameter to the method.


This should always be checked and should throw IllegalArgumentException,
with the messages for the programmer about what the wrong value was and
what range it should of been, as I mention above.

there is not going to be a GUI on which
to display the message for that error. So how should that be handled?


It's OK to wrap the entire main method with a try-catch that results in
a bland "Internal error, please call technical support" message so the
user never sees internal error messages.

Again, I'm assuming that errors like this shouldn't be logged.


Log everything. Then, when the user calls technical support, the
support technician can ask the user to email the logs, so tech support
can figure out what went wrong.

3. Serious errors causes by programmer error.


Throw an exception. Let higher level code decide if it wants to log or
propagate the exception. This makes testing much easier. And higher
level code will be more flexible because it decides how the program
flows, not you. At the higher level, log it when you no longer
propagate it.

4. Really bad errors not caused by the programmer.

I assume that ALL such situations should be logged.


Throw an exception, let higher level code deal with it. Always log it
at the higher level, and then display an appropriate error message.

What notifications should users receive in such cases? What notifications
should batch programs make in those cases?


Depends on whether your user is technical or not. Technical users might
appreciate the error trace if they have access to your source code.
Non-technical users probably want to call tech support. Log these at
the higher levels of code, throw at the lower levels. Because technical
vs. non-technical might change over the life of the software and you
don't want to have to hunt down every log and throw, just a few at the
top level.
 
R

Rhino

Lew said:
You just will come up with any excuse not to read, won't you?

First it was that you can't afford it. Then people (repeatedly) suggest a
way to do it for free and you now claim that there isn't enough time in
those situations to read. Oh, and what was your excuse not to use a
library?


Yeah, situations that involve a programmer actually willing to do what it
takes to learn their craft. Except for those situations, I guess the
suggestions are pretty useless.

Oh please! Could YOU pick up a significant amount of detail - either via
memorization or making notes - from a 400 or 500 page book in just a couple
of hours of reading?

Do YOU have so much influence that you can put in a request for an
interlibrary loan and have the book appear in a mere day or two?

If so, my hat is off to you for you are clearly a superhuman, not a mere
mortal like me.
 
R

Rhino

markspace said:
In general, log everything, and throw on everything. This contradicts
some advice you've got already on this thread. I'll try to justify my
reasons.




As a special case, when validating an input value it isn't really "wrong"
for the value to be incorrect, so it's OK to return true or false and not
throw an exception. If you receive a bad value where you weren't
expecting it, throw an exception.




As others have mentioned, I like this one best too. Acknowledging a
pop-up is annoying and takes a "user gesture." Too many user gestures and
a program is just plain bothersome and hard to use.




I happen to be dealing with a JEE app that was written by someone who
appears to be a decent but inexperienced coder. All code captures any
exception, prints a stack trace, and then just returns. This results in a
hung app if something important fails, and it happens that the database is
unstable right now. But the servlet can't know that the database has gone
off-line, because there's no exception, so the servlet just calls the next
method and everything hangs.

Throwing exceptions instead of printing a message and then swallowing them
would have resulted an app that was easier to test, rather than one that
just timed out but gave no indication to the tester when or why.

Throw all exceptions, until you get to the user's level, then do something
to make a nice error result. In this case the servlet should have caught
the error, logged it, and then dispatch a nice error page instead of just
hanging forever.




Throw an exception, and format its message for the programmer. Include
all relevant arguments and any relevant internal objects too, even if
private.

For example, on an array index out of range exception, return the index
value the programmer passed in, so the programmer can see what they did,
and the size of the array that was exceeded, so the programmer can see
what they should have done.

Let the higher level code decide what message the user should see.




I log everything. When I'm writing code, I'm normally writing the unit
test at the same time. I crank up the log level to FINER or ALL, put
everything I need to see in log messages, and add a ConsoleHandler so I
can see it easily. Then when it all seems to work, I reduce the log level
but I leave that logging still there. That way all the work I went
through when deciding what to log is not lost, and it's all still there if
I or someone else should need it again.

Don't ignore optimization: Use "isLoggable(Level)" everywhere and
minimize the places where you have to call it, but don't stint either.
Your time is more valuable that the CPU's.

This is the true value of "log everything," imo. Having a routine that's
already well instrumented when you need to go back to it and debug
something is a great time-saver in the long run.




This should always be checked and should throw IllegalArgumentException,
with the messages for the programmer about what the wrong value was and
what range it should of been, as I mention above.




It's OK to wrap the entire main method with a try-catch that results in a
bland "Internal error, please call technical support" message so the user
never sees internal error messages.




Log everything. Then, when the user calls technical support, the support
technician can ask the user to email the logs, so tech support can figure
out what went wrong.




Throw an exception. Let higher level code decide if it wants to log or
propagate the exception. This makes testing much easier. And higher
level code will be more flexible because it decides how the program flows,
not you. At the higher level, log it when you no longer propagate it.




Throw an exception, let higher level code deal with it. Always log it at
the higher level, and then display an appropriate error message.




Depends on whether your user is technical or not. Technical users might
appreciate the error trace if they have access to your source code.
Non-technical users probably want to call tech support. Log these at the
higher levels of code, throw at the lower levels. Because technical vs.
non-technical might change over the life of the software and you don't
want to have to hunt down every log and throw, just a few at the top
level.

Thank you for your suggestions, Markspace!

I'm really attracted to the approach you described since it seems pretty
clear and logical to me. But I'm also intimidated by the inevitable backlash
that is going to result from your post. I'd just about bet my life that
several people will jump in and argue persuasively that various aspects of
it are completely wrong and propose a different approach, at least for the
parts they dislike and maybe for the whole thing. (And of course some people
have already proposed different approaches that are different.)

I'm simply not sufficiently experienced with many of these issues to be
confident that I will pick the right approach on my own; that's why I ask
this kind of question on the newsgroup. I'm hoping a concensus will emerge
and then I'll go with that, or at least some version of it.

Do you know the saying "A man with one watch always knows what time it is; a
man with two (watches) is never quite sure". That's one of my favourites
because I've observed that literally on many occasions. I also see it as a
metaphor for the situation I'm in: each piece of advice (or "time") comes
with an assurance that it is the best but each one has some aspect that
someone else disagrees with. So I end up just not knowing which way to
proceed.

Well, I've been around long enough to know that there won't ever be complete
agreement on anything as complex as error handling - there are plenty of
different views on routine GUI input errors alone - so I am obviously just
going to have to pick the approach that seems most logical to me after a few
more people have had their say.

I will inevitably have chosen the wrong approach in some people's eyes so
I'll just accept that. If I show my code to a prospective employer and
he/she takes issue with it, I'll simply tell the truth: I explored options
and chose the one that seemed best at the time for my own code. I will
assure them that I will do it the way they want for their system if they
hire me.

I don't see how I can go too far wrong with that approach.

Thanks again for your suggestions!
 
E

Eric Sosman

Oh please! Could YOU pick up a significant amount of detail - either via
memorization or making notes - from a 400 or 500 page book in just a couple
of hours of reading?

No. And it's clear that *you* can't, not even with far more
time spent studying:

May 17, 2010: "I used to know how to [use instanceof]
several years ago"

Feb 13, 2006[!]: "I've been writing Java code [...] for
several years now and feel that I could do a decent job
at an intermediate level"

Dec 22, 2005[!!]: "I've been writing Java for several years"

Dec 6, 2004[!!!]: "I have been writing Java for several
years and am fluent enough that I don't have to post
questions here very often" [!!!!!!!!]

If "several plus five and a half" years of Java experience have
left you unaware of instanceof, baffled by the use of interface types,
and still asking long-winded elementary questions about exceptions,
I'd guess that you will not benefit from any book, however excellent.
Something in your brain resists Java, and you'd just be wasting time
and money trying to pound square-pegged Java into your head's round
hole. Forget Java and take up set design or viola playing or politics
or something -- there must be *some* field for which you have more
talent, because your talent for Java seems small indeed.
 
L

Lew

Oh please! Could YOU pick up a significant amount of detail - either via
memorization or making notes - from a 400 or 500 page book in just a couple
of hours of reading?

Yes, if that couple of hours is repeated, say, weekly, and accompanied with
actual practice in the art. In fact, that pretty much describes how I learn
to program Java. I don't spend much money on books at all, so when I do buy
it has to really be worth it.

I certainly didn't get this good at Java by protecting my ego at the expense
of my skill.

Nor by making pathetic excuses that somehow not buying books should in any way
impede my learning.
Do YOU have so much influence that you can put in a request for an
interlibrary loan and have the book appear in a mere day or two?

Maybe a week. And that's just the normal public library, no special influence
needed. So?

How is never better than a week's delay?
If so, my hat is off to you for you are clearly a superhuman, not a mere
mortal like me.

Oh, please!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top