Re: Java language and library suggestions
Lew wrote:
Log the exception and return gracefully.
public void Foo()
{
try
{
invokeMethodThatThrowsIOE();
}
catch ( IOException exc )
{
final String msg = "IOException: "+ exc.getLocalizedMessage();
logger.error( msg );
return;
Patricia Shanahan wrote:
I don't like return here, because the rest of the code may be depending
on Foo having done something that has not been done. It could lead to
bad outcomes, such as the wrong thing being written to a file that
survives beyond the program run. Wouldn't a runtime exception be better?
Or even a System.exit call.
}
}
A very valid point. There are times when a return is appropriate, and there
are times when it isn't.
Often having a System.exit() is the wrong thing to do - for example, in a web
application. One has to apply situational wisdom and figure out a way to
gracefully return to a valid program state that will not disturb the user.
The situation is easier when the method returns a reference. Returning a
sentinel value like 'null' or an enum 'ERROR' value can help invoking code
decide where to go next.
I try to avoid simple propagation of exceptions, checked or runtime. It makes
it hard to keep a program running in a useful way. I prefer to trap and log
exceptions, then branch to a valid state, which often is a user-friendly error
screen.
You could put an assertion after the catch block but it is hard to
think what one would assert inside the catch block. What would be the
invariant there?
http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html#usage-control
suggests
assert false; // Execution should never reach this point!
to mark a place in the code that should never be reached.
That works, but I also like to put a more affirmative assertion after the
catch block.
--
Lew