简体   繁体   English

如果我的父班引发异常,我的孩子班必须抓住吗?

[英]If my parent class throws an exception, must my child class catch it?

I have a parent class which throws some exceptions, not handling those exceptions in the parent class. 我有一个抛出一些异常的父类,而不在父类中处理那些异常。 And now I am inheriting this parent class. 现在,我继承了这个父类。 Is it necessary to catch exceptions thrown by my parent class? 是否有必要捕获我的父类抛出的异常?

You should catch all of your exceptions where they occur. 您应该捕获所有发生的异常。 Where you think that a code could throw an exception make a try-catch statement and handle the exception. 在您认为代码可能引发异常的地方,请执行try-catch语句并处理该异常。 you don't want to have exceptions and do not handle them. 您不想有异常并且不处理它们。

Gotta catch 'em all! 需要把他们全都抓到!

覆盖的方法只能抛出其覆盖的父方法抛出的异常或期望的子类。

If your parent class throws an Exception then your child class may either throw the exception or you can also catch the exception appropriately in the over-riding method. 如果您的父类抛出一个异常,那么您的子类可能会抛出该异常,或者您也可以在重写方法中适当地捕获该异常。

Overridden methods can throw only the subclasses of exception thrown by the method in superclass, and it cannot throw the superclass of exception thrown by the method in superclass. 重写的方法只能抛出超类中方法抛出的异常的子类,而不能抛出超类中方法抛出的异常的超类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 异常处理:父类异常也会捕获子异常吗? - Exception Handling: Will parent class exception catch child exception too 将捕获异常捕获该异常的父类 - Will catching an exception catch a parent class of that exception 在我的例子中,从子类中调用父抽象类中的函数 - Invoke function in parent abstract class from child class in my case 父子类StackOverflowError异常 - parent child class StackOverflowError exception 如果父方法抛出检查异常,那么是否必须在子类中抛出相同的异常? - If parent method throws checked exception, then is it compulsory to throw the same exception in child class? 如何在MainActivity类中添加throws异常子句? - How can I add a throws exception clause in my MainActivity class? 很难让我的孩子 class 准确地覆盖我的父母 class - Having a hard time getting my child class to accurately overwrite my parent class 如何创建必须引发或捕获特定异常的类。 - how to create a class in which it is necessary to throws or catch a specific exception. 父/子序列化本地类不兼容异常 - Parent/Child Serialization local class incompatible Exception 为什么每当我触发父 Class - Android 中的操作时,我的子 Class 方法总是被调用? - Why is my Child Class method is being calling always whenever I trigger an action in the Parent Class - Android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM