try、catch和finally

  • try块:用于捕获异常。
    • 后面可以有0个或多个catch块。
    • 只能有0个或1个finally块。
    • try块后面,如果没有catch块,则后面必须有一个finally块。
    • 执行代码捕获异常后,进入catch块,try中出现异常代码处后面的代码不会再继续执行。
  • catch块:用于处理处理try中捕获的异常。
    • 可以有多个catch块,进入一个catch块后,执行完毕后,如果有finally块,则进入finally块。即使后面还有catch块,也不会再进入其他catch块。
  • finally块:无论是否捕获或处理异常,finally块中的代码都会被执行。
    • 当try块中或者catch块中遇到return语句时,先执行完finally里面的代码后,再执行return返回语句。

可以有多个catch块,并且try块后面,只能有0个或1个finally块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void main(String[] args) {
try {
System.out.println("try...");
}catch (ArithmeticException e){
System.out.println("ArithmeticException...");
}catch (NullPointerException e){
System.out.println("NullPointerException...");
}
finally {
System.out.println("finally...");
}
}

//输出结果:
//try...
//finally...

try块后面,如果没有catch块,则后面必须有一个finally

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
try {
System.out.println("try...");
}
finally {
System.out.println("finally...");
}
}

//输出结果:
//try...
//finally...

执行代码捕获异常后,进入catch块,try中出现异常代码处后面的代码不会再继续执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void main(String[] args) {
try {
System.out.println("try...");
int a = 0;
String str = null;
System.out.println(str.toString());
a = a / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException...");
} catch (NullPointerException e) {
System.out.println("NullPointerException...");
} finally {
System.out.println("finally...");
}
}

//输出结果:
//try...
//NullPointerException...
//finally...

当try块中或者catch块中遇到return语句时,先执行完finally里面的代码后,再执行return返回语句。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void main(String[] args) {
try {
System.out.println("try...");
return;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException...");
} catch (NullPointerException e) {
System.out.println("NullPointerException...");
} finally {
System.out.println("finally...");
}
}

//输出结果:
//try...
//finally...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static void main(String[] args) {
try {
System.out.println("try...");
int a = 0;
a = a / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException...");
return;
} catch (NullPointerException e) {
System.out.println("NullPointerException...");
} finally {
System.out.println("finally...");
}
}

//输出结果:
//try...
//ArithmeticException...
//finally...