Re: Exception handling question
On 4/20/2010 8:29 AM, mike wrote:
Hi,
I have written a tool in java. To run the tool I do:
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);
}
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.
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");
} catch (IOException e) {
throw new MyToolException("File Could not be read");
}
}
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
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).
Or is there an other way to do this? I am using jdk1.4.2 ( and I am
stuck with it :-( ).
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.
--
Eric Sosman
esosman@ieee-dot-org.invalid