抛出异常的编译错误
compilation error with throwing exception
public class A {
public void f(A a) {
System.out.print("in A ");
}
}
public class B extends A {
public static void main(String[] args) {
B b = new B();
A a = new A();
b.f(b);
b.f(a);
}
}
为什么在B中添加如下方法class会出现编译错误?
众所周知,如果方法抛出某些东西,则不必在方法头中声明...
public void f(A a) {
System.out.println("in B");
throw new java.io.IOExeption();
}
It's known that if method throws something, it doesn't have to be declared in the method header
这仅适用于未经检查的异常。您的方法抛出 IOException
,这是一个 已检查异常 ,因此您必须捕获它或声明抛出它,否则编译将失败。
public class A {
public void f(A a) {
System.out.print("in A ");
}
}
public class B extends A {
public static void main(String[] args) {
B b = new B();
A a = new A();
b.f(b);
b.f(a);
}
}
为什么在B中添加如下方法class会出现编译错误?
众所周知,如果方法抛出某些东西,则不必在方法头中声明...
public void f(A a) {
System.out.println("in B");
throw new java.io.IOExeption();
}
It's known that if method throws something, it doesn't have to be declared in the method header
这仅适用于未经检查的异常。您的方法抛出 IOException
,这是一个 已检查异常 ,因此您必须捕获它或声明抛出它,否则编译将失败。