不一定每个 try 块后面都必须跟一个 catch 块。 它后面应该跟一个 catch 块或 finally 块。 所以任何可能抛出的异常都应该在方法的 throws
子句中声明。 考虑以下示例:
public class Main {
public static void main(String[] args) {
try {
int a = 1;
System.out.println(a / 0);
} finally {
System.out.println("rest of the code...");
}
}
}
运行结果:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...