Re: Exception handling question
mike wrote:
I have written a tool in java [sic]. To run the tool I do:
It's spelled "Java".
MyTool tool = new MyTool();
tool.process();
In my code there is risk that code will throw IOException since it
will not be able to read a file. Or it can be a
TransformerConfigurationException in my xsl transformer. If a step
fails I would like stop continuing the processing since all other
further steps will be failing.
I am thinking of doing something like:
try {
MyTool tool = new MyTool();
tool.process();
} catch (MyToolException mte){
mte.printStackTrace();
System.exit(0);
}
Where is the logger?
Eric Sosman wrote:
Seems pointless, since this is pretty much what will happen
if the exception remains uncaught and just propagates out to the
ultimate handler. If the caller plans to catch MyToolException
and do something else with it, this would force an exit -- but
preventing the caller from catching even if it wants to is a
fairly unfriendly thing to do.
Depends on how low level the intended caller is.
mike wrote:
Example of code in tool that gives a IOException:
private static void copy(String from, String to) {
try {
[...]
} catch (FileNotFoundException ex) {
throw new MyToolException("File Could not be found");
Where is the logger?
} catch (IOException e) {
throw new MyToolException("File Could not be read");
Where is the logger?
Eric Sosman wrote:
Ugh. If the original exception had any useful information
about the ultimate problem, you have carefully thrown it all
away and thus made the job of correcting the problem harder.
"Doctor, my ear hurts." "Left or right?" "Not telling, nyaah!"
The simplest thing to do is just to let the IOException go
on its merry way, carrying whatever information it can. If you
No, no, no. Wrap-and-rethrow is correct - all the caller should care about is
the failure of 'copy()', not the reason for the failure, which should have
been *logged* at the low level.
Hello!
really want to throw MyToolException instead, at the very least
you should have the IOException be the "cause" (see the Javadoc
for java.lang.Throwable).
Absolutely! Failure to chain causes is right up there with failure to log.
mike wrote:
Or is there an other way to do this? I am using jdk1.4.2 ( and I am
stuck with it :-( ).
Eric Sosman wrote:
The version *after* that one reached end-of-life two years
ago, and went off support six months ago. It's your funeral
and you can select the hymns, but don't expect many people to
sing along.
Since there is no difference in exceptions between Java 1.4 and later
versions, this is a difference that makes no difference. Go ahead and give
your advice based on something more recent than Neolithic Java; it'll still apply.
--
Lew