在 Java 中,有一些异常需要 throws 语句:
public void myMethod() throws IOException {
throw new IOException("Error!");
}
而其他人则不然:
public void myOtherMethod() {
throw new IllegalArgumentException("Error!");
}
public void myThirdMethod() {
throw new Error("Error!");
}
如果没有throws
,第一种方法将无法编译声明。
判断是否Exception
的标准是什么?/Error
需要 throws
声明?
最佳答案
编译器检查和提示的异常在java中称为检查异常。
At compile time, the java compiler checks that a program contains handlers for checked exceptions. Java compiler analyzes by which checked exceptions can result from execution of a method or constructor.For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class or its superclasses of that exception.
从 JLS 了解更多信息:http://docs.oracle.com/javase/specs/jls/se5.0/html/exceptions.html
IOException 是一个检查异常,因此 java 编译器要求您捕获它或抛出它。而 IllegalArgumentException 是一个运行时异常,编译器不会检查或提示。
关于java - 哪些异常需要方法的 throws 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17726033/