我正在学习java中的异常处理(基本上是继承) [英] I am learning the Exception handling in java (basically in inheritance)
问题描述
只看下面的程序..
import java.io. *;
import java.rmi。*;
class class1
{
public void m1()throws RemoteException
{
System.out.println(class1中的m1);
}
}
class class2 extends class1
{
public void m1()throws IOException
{
System.out.println(class2中的m1);
}
}
class ExceptionTest2
{
public static void main(String args [])
{
class1 obj = new class1();
try {
obj.m1();
}
catch(RemoteException e){
System.out.println(ioexception);
}
}
}
编译时间错误.....无法覆盖m1()方法
现在,如果我将父类中的RemoteException替换为IOException,反之亦然。然后它正在编译。
任何其他已检查的异常组合在这里都不起作用,即使我使用的是同一级别的已检查异常。
现在我很困惑,为什么压倒只发生在一个案件中,而不是在其他情况下???
我将非常感谢您的回答。
当重写抛出异常的方法时,您只能抛出相同的异常或该异常的更具体的子类型。 / p>
RemoteException是IOException的子类型。因此,当父方法抛出IOException时,您的子方法可以抛出RemoteException。
您也可以通过逻辑思考它。如果子方法抛出比父方法更广泛的异常,则该方法可能抛出与父方法不匹配的异常。
just look at program below..
import java.io.*;
import java.rmi.*;
class class1
{
public void m1() throws RemoteException
{
System.out.println("m1 in class1");
}
}
class class2 extends class1
{
public void m1() throws IOException
{
System.out.println("m1 in class2");
}
}
class ExceptionTest2
{
public static void main(String args[])
{
class1 obj = new class1();
try{
obj.m1();
}
catch(RemoteException e){
System.out.println("ioexception");
}
}
}
compile time error.....can not override m1() method
Now if I replace RemoteException in parent class with IOException and vice versa in child class. Then it is compiling.
Any other checked exception combinations are not working here, evenif I am using checked exception which are at same level.
Now I am confused why overriding is taking place only in one case, not in other cases??? I will realy appreciate your answer.
When overriding a method that throws an Exception you can only throw the same Exception or a more specific subtype of that Exception.
RemoteException is a subtype of IOException. Therefore when the parent method throws IOException your child method can throw RemoteException.
You can also think it through logically. If a child method threw a broader Exception than the parent method, then the method might throw an Exception that doesn't match the parent.
这篇关于我正在学习java中的异常处理(基本上是继承)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!