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?

4

3 回答 3

8

您可以 throwUnchecked exceptions而无需将它们添加到方法的原型中。

未经检查的异常是任何继承自RuntimeException. 那是你想做的吗?

于 2010-09-13T21:13:26.223 回答
6

您可以抛出 RuntimeException 的子类的实例,编译器不会检查这些实例。

然而,话虽如此,空异常规范是基类方法契约的一部分。子类需要满足契约,以便子类实例可以在任何使用超类类型的代码中使用。(这被称为Liskov 替换原则。)

于 2010-09-13T21:13:15.460 回答
3

您只需要声明和捕获“已检查异常”。您不需要声明或显式捕获 RuntimeExceptions。因此,您可以抛出 RuntimeException 并在层次结构中的任意位置捕获它。

于 2010-09-13T21:14:16.453 回答