Java程序设计进阶之路二:异常捕捉机制与捕捉到的异常
一、异常捕捉机制
捕捉异常
try {
// 可能产生异常的代码
} catch (Type1 e1) {
// 处理异常的代码
} catch (Type2 e2) {
// 处理异常的代码
} catch (Type3 e3) {
// 处理异常的代码
}
二、示例代码
1.主函数中添加异常机制
public class ArrayIndex {
public static void f(){
int[] a = new int[5];
a[5] = 5;
System.out.println("f()无异常且被调用!");
}
public static void g() {
int i = 1;
if(i<10){
f();
System.out.println("g()调用f()!");
}
}
public static void h() {
g();
System.out.println("h()调用g()!");
}
public static void main(String[] args) {
try {
h();
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("啊哦,数组越界了!");
}
}
}
运行结果:
啊哦,数组越界了!
可以看到由于f()中的数组越界异常,程序的函数调用都在f()处终止,但主函数并没有停止,而是执行catch后的语句。
2.向函数f()中添加异常捕捉,再试一下
public class ArrayIndex {
public static void f(){
try {
int[] a = new int[5];
a[5] = 5;
System.out.println("f()无异常且被调用!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("f()中异常被捕捉!");
}
}
public static void g() {
int i = 1;
if(i<10){
f();
System.out.println("g()调用f()!");
}
}
public static void h() {
g();
System.out.println("h()调用g()!");
}
public static void main(String[] args) {
try {
h();
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("啊哦,数组越界了!");
}
}
}
运行结果:
f()中异常被捕捉! g()调用f()! h()调用g()!
向f()中添加了异常捕捉机制后,虽然数组越界异常仍然存在,但是catch语句捕捉到了这个异常并执行力其后的语句!
3.函数h()添加异常捕捉
public class ArrayIndex {
public static void f(){
int[] a = new int[5];
a[5] = 5;
System.out.println("f()无异常且被调用!");
}
public static void g() {
int i = 1;
if(i<10){
f();
System.out.println("g()调用f()!");
}
}
public static void h() {
try {
g();
System.out.println("h()调用g()!");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("异常,结束!");
}
}
public static void main(String[] args) {
try {
h();
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("啊哦,数组越界了!");
}
}
}
运行结果:
异常,结束!
可以知道主函数try后语句调用的h()中出现异常且被捕捉,执行后程序结束。
三、今日总结
附上今天的图片总结:异常捕捉机制


浙公网安备 33010602011771号