1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
try
{
normal statement;
//1.
exception occurred;
//2.
return
"try"
;
}
catch
(Exception ex) {
normal statement;
//3.
return
"catch"
;
}
finally
{
normal statement;
//4.
return
"finally"
;
//5. -->End
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
try
{
normal statement;
//1.
exception occurred;
//2.
return
"try"
;
}
catch
(Exception ex) {
normal statement;
//3.
return
"catch"
;
//5. -->End
}
finally
{
normal statement;
//4.
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
try
{
normal statement;
//1.
exception occurred;
//2.
return
"try"
;
}
catch
(Exception ex) {
normal statement;
//3.
throw
Exception;
}
finally
{
normal statement;
//4.
return
"finally"
;
//5. -->End
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
try
{
normal statement;
//1.
exception occurred;
//2.
return
"try"
;
}
catch
(Exception ex) {
normal statement;
//3.
throw
Exception;
}
finally
{
normal statement;
//4.
throw
Exception;
//5. -->End
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
try
{
normal statement;
//1.
exception occurred;
//2.
return
"try"
;
}
catch
(Exception ex) {
normal statement;
//3.
throw
Exception;
//5. -->End
}
finally
{
normal statement;
//4.
}
|
结论:
1、Try-catch-finally中的finally一定会执行,而且,一定优先于try/catch中的return/throw语句执行,除非系统崩了或者程序使用System.exit(0)强行终止;
2、finally中如果有return或throw,则优先处理finally中的return/throw;
3、return和throw,从语句流转的角度上看,这两个语句是等效的;
4、finally中没有return或throw,则程序会回溯到try/catch中执行return/throw语句。如果当初是catch=>finally,则回溯到catch中执行return/throw;如果是try=>finally,则回溯到try中执行return/throw;如果try/catch中都不存在return/throw,则跳出try-catch-finally语句体继续执行后续代码。
本文转自 rickqin 51CTO博客,原文链接:http://blog.51cto.com/rickqin/1868754