class MyException extends Exception {
MyException() {}
MyException(String msg) { super(msg);}
}
public class NewException {
static void f() throws MyException {
System.out.println("throwing exception from f()");
throw new ClassCastException();
}
static void g() throws MyException {
System.out.println("throwing exception from g()");
throw new MyException("parametrized ");
}
public static void main(String ...strings ) {
try {
f();
}
catch(MyException e) {
e.printStackTrace(System.out);
}
try {
g();
}
catch(MyException e) {
e.printStackTrace(System.out);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在函数f()中,我指定将抛出"MyException"异常,实际上我抛出了一些与MyException无关的其他异常,但编译器仍然没有抱怨.为什么?
ClassCastExceptionextends RuntimeException,表示它未被选中,因此编译器不需要您处理它.
来自Javadoc RuntimeException:
一个方法不需要在其throws子句中声明RuntimeException的任何子类,这些子类可能在方法执行期间抛出但未捕获.