下面是包含一个throws子句的方法声明的通用形式:
type method-name(parameter-list) throws exception-list{
// body of method
}
这里,exception-list是该方法可以抛出的以有逗号分割的异常列表。
下面是一个不正确的例子。该例试图抛出一个它不能捕获的异常。因为程序没有指定一个throws子句来声明这一事实,程序将不会编译。
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
为编译该程序,需要改变两个地方。第一,需要声明throwOne( )引发IllegalAccess Exception异常。第二,main( )必须定义一个try/catch 语句来捕获该异常。正确的例子如下:
// This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}