>You can throw a compile-time superclass or interface type, and then
>catch specific runtime-type exceptions. Or you could even catch a
>generic exception type and then use instanceof in your handler.
I understand this... if I say:
throw new UnsupportedEncodingException();
I can handle it with:
catch (IOException e)
Is the inverse true? E.g.
public void thrower()
throws IOException {
...
some method call that throws UnsupportedEncodingException
...
}
public void catcher() {
try {
thrower();
} catch (UnsupportedEncodingException e) {
...
}
}
Or do I have to do like:
catch (IOException e) {
if (e instanceof UnsupportedEncodingException) {
...
} else {
...
}
}
Mike Schilling - 09 May 2006 21:41 GMT
>>You can throw a compile-time superclass or interface type, and then
>>catch specific runtime-type exceptions. Or you could even catch a
[quoted text clipped - 24 lines]
> }
> }
This will work fine. The compiler complains only when you try to catch
something that (logically) can't be thrown, say
void thrower() throws IOException
try
{
thrower();
}
catch (ParseException ex) // compilation-time error
{
}
>> How do people generally code this? For the throwing method, do you specify
>>
[quoted text clipped - 8 lines]
> There's one idea that says you should always program to the highest
> abstraction that is suitable to your needs.
That's a good rule of thumb. However there's a twist here: when writing
a method you probably do not know what code will be calling it and how
it will want to do error handling.
> Then there's the idea that your error handling should be as complete as
> you can possibly make it.
Yes!
> You can throw a compile-time superclass or interface type, and then
> catch specific runtime-type exceptions. Or you could even catch a
> generic exception type and then use instanceof in your handler.
I'd rather not use instanceof although I can see how that makes code
simpler in some cases. Personally I'd prefer to rather refactor
handling code into another method if it's worth it (enough LOC) and
catch individual exceptions.
> Personally, if I had no means or no plans to handle these specific
> errors, I'd just throw the general type.
IMHO you're mixing throwing and handling here. If you think modularly
then the author of the method need not possibly know what callers want
to do (i.e. catch specific or general). Code is better than
documentation so I recommend to list all exceptions in the throw clause.
Callers then exactly see what they can expect and they can still just
catch IOException or declare IOException on their method if that's
sufficient for them.
> If all your handlers end up
> reporting the error the same way, you're not really buying anything
> except duplicated catch blocks anyway.
As I said, listing all individual exceptions doesn't preclude just
catching IOException.
Kind regards
robert