views:

96

answers:

3

This may be a ridiculous Java question about exception handling, but I have a UI actor (an Android Activity) that is requesting services from my subclass of ContentProvider. The subclass wants to throw some exceptions when sd-card is full, sd-card is missing, network i/o errros, etc. However, when I code the CP-subclass to throw my exceptions, the compiler offers to add the exceptions to the CP class. Obviously, I don't want to modify the base class, but I want the UI to catch the sub-class' exceptions.

Make sense? Is this possible? If not, is there a better pattern for my service subclass to get its throwable object back to the UI?

+6  A: 

You could throw instances of subclasses of RuntimeException, which are not checked by the compiler.

However, that being said, the empty exception specification is part of the contract of the base class methods. It is desirable for subclasses to satisfy the contract, so that subclass instances can be used in any code that uses the superclass type. (This is known as the Liskov substitution principle.)

Andy Thomas-Cramer
+1 for being the only one who noted necessity to follow base class' contract.
Nikita Rybak
That makes sense. Although I don't entirely know what I need to code, I do agree with extending the methods appropriately, such that my class is a 'valid' subclass. I will study on this.
mobibob
+7  A: 

You can throw Unchecked exceptions without having to add them to the prototype of the method.

An unchecked exception is any exception that inherits from RuntimeException. Is that what you wanted to do?

Here Be Wolves
Yes, that is what I want. I actually starting coding that as my "work around" while waiting for the answer -- but since I got three quick responses, I now know it is not a work around, but the correct solution.
mobibob
yay for you! :D
Here Be Wolves
+3  A: 

You only need to declare and catch "checked exceptions". You do not need to declare or explicitely catch RuntimeExceptions. So you can throw a RuntimeException and catch it whereever you like up in the hierarchy.

Peter Tillemans