Re: How to tell caller of an error if you cant change the signature
of a method
On Apr 14, 9:23 am, Lew <l...@lewscanon.com> wrote:
Owen Jacobson wrote:
For completeness, here's an ExceptionHandler that knows about
IOExceptions:
public interface ExceptionHandler {
public void handleException (Exception e);
}
public class IOExceptionHandler implements ExceptionHandler {
public void handleException (Exception e) {
try {
throw e;
Or you could use 'if ( e instanceof IOException )', which preserves the st=
ack
frame of the original exception and perhaps would be quicker, not that spe=
ed
matters to exception handling.
Rethrowing an exception does not, under the Sun JVM, clear its
stacktrace:
public class Foo {
public static void main(String[] args) {
Handler h = new Handler();
try {
throw new Exception();
} catch (Exception e) {
h.handle(e);
}
}
}
class Handler {
public void handle(Exception e) {
try {
throw e;
} catch (Exception ee) {
e.printStackTrace();
}
}
}
//--
Prints:
java.lang.Exception
at Foo.main(Foo.java:6)
The stacktrace is actually populated when the exception is created;
one of the problems with creating an Exception object in advance is
that the stacktrace will not indicate where it was thrown!
There are some clever uses for this behaviour that I will leave it to
you to discover. :)
} catch (IOException ioe) {
System.err.println ("Handled an IOException: " + ioe);
} catch (Exception e) {
// Unexpected variety of failure here.
throw new RuntimeException (e);
}
}
}
As illustrated, the design of ExceptionHandler as written demands that
implementations be prepared for *any* Exception, even if the caller
will only ever pass some specific type of Exception. The design could=
be improved by providing specialized ExceptionHandler interfaces for
different implementations of IFoo, such that each handler only has to
deal with the exceptions that can actually be thrown.
Generics?
public interface ExceptionHandler < E extends Exception >
{
public void handle( E e );
}
...
Pretty much any time I see run-time type checking built into the code, I
think, "This is a job for generics!"
Well, a job for polymorphism primarily, and generics frequently.
That works for single exceptions (and it's probably how I'd do it
under the constraints), but not all services only throw one type of
exception that's more specific than Exception. Other approaches are
necessary if you want to make the exception handler interface specific
to the exceptions that can actually be thrown, for these services.
-o