是否可以通过不抛出异常的基类的调用方法来抛出java异常?
这可能是一个关于异常处理的可笑的 Java 问题,但我有一个 UI actor(一个 Android Activity)正在从我的 ContentProvider 子类请求服务。当 sd 卡已满、sd 卡丢失、网络 i/o 错误等时,子类想要抛出一些异常。但是,当我编写 CP 子类以抛出异常时,编译器会建议将异常添加到CP类。显然,我不想修改基类,但我希望 UI 捕获子类的异常。
有道理吗?这可能吗?如果没有,我的服务子类是否有更好的模式将其可抛出对象返回到 UI?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以抛出
未经检查的异常
,而无需将它们添加到方法的原型中。未经检查的异常是继承自
RuntimeException
的任何异常。这就是你想做的吗?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?您可以抛出 RuntimeException 子类的实例,编译器不会检查这些实例。
然而,话虽这么说,空异常规范是基类方法契约的一部分。子类最好满足契约,以便子类实例可以在任何使用超类类型的代码中使用。 (这称为里氏替换原则。)
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.)
您只需要声明并捕获“受检查的异常”。您不需要声明或显式捕获 RuntimeException。因此,您可以抛出 RuntimeException 并在层次结构中的任何位置捕获它。
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.