class TestSystemException {
public static void main(String[] args) {
int num[] = new int[2];
for (int i = 1; i < 3; i++) {
num[i] = i;
System.out.println("num[" + i + "]=" + i);
}
}
}
二、抛出与捕捉
处理异常就两件事:抛出(throw)和捕捉(catch)。运行出错且能对应到某个预定义异常类时,系统自动 new 一个该异常对象,这叫抛出。程序里若找到处理代码,就把对象交给它,这叫捕捉。找不到则交给运行时默认处理:先打印描述字符串,再终止程序。
自定义异常必须是 Throwable 或 Exception 的子类。一般声明两个构造方法:无参,以及以字符串为参数(字符串应反映异常信息)。自定义异常同样要用 try-catch 捕获,但必须由用户自己 throw new MyException()。
class Exception_exp {
public static void main(String[] args) {
try {
System.out.println("2+3=" + add(2, 3));
System.out.println("-8+10=" + add(-8, 10));
} catch (Exception e) {
System.out.println("Exception is " + e);
}
}
public static int add(int n, int m) throws UserException {
if (n < 0 || m < 0) throw new UserException();
return n + m;
}
}
class UserException extends Exception {
UserException() {
super("数据为负数");
}
}