Search code examples
javasubclassthrowable

Is it possible to throw a java exception through the calling method of a base class that does not throw exceptions?


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?


Solution

  • 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.