以下所示:html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
class Exc{
int a;
int b;
}
public class Except {
@SuppressWarnings(
"finally"
)
static int compute (){
Exc e =
new
Exc();
e.a = 10;
e.b = 10;
int res = 0 ;
try
{
res = e.a / e.b;
System.out.println(
"try ……"
);
return
res + 1;
}
catch
(NullPointerException e1){
System.out.println(
"NullPointerException occured"
);
}
catch
(ArithmeticException e1){
System.out.println(
"ArithmeticException occured"
);
}
catch
(Exception e3){
System.out.println(
"Exception occured"
);
}finally{
System.out.println(
"finnaly occured"
);
}
System.out.println(res);
return
res+3;
}
public static void main(String[] args){
int b = compute();
System.out.println(
"mian b= "
+b);
}
}
|
輸出:java
1
2
3
|
try
……
finnaly occured
mian b= 2
|
結論: 若是沒有異常, 則執行try 中的代碼塊,直到 try 中的 return,接着執行 finally 中的代碼塊,finally 執行完後 , 回到try 中執行 return 。退出函數。程序員
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
class Exc{
int a;
int b;
}
public class Except {
@SuppressWarnings(
"finally"
)
static int compute (){
Exc e =
new
Exc();
// e.a = 10;
// e.b = 10;
int res = 0 ;
try
{
res = e.a / e.b;
System.out.println(
"try ……"
);
return
res + 1;
}
catch
(NullPointerException e1){
System.out.println(
"NullPointerException occured"
);
}
catch
(ArithmeticException e1){
System.out.println(
"ArithmeticException occured"
);
}
catch
(Exception e3){
System.out.println(
"Exception occured"
);
}finally{
System.out.println(
"finnaly occured"
);
}
System.out.println(res);
return
res+3;
}
public static void main(String[] args){
int b = compute();
System.out.println(
"mian b= "
+b);
}
}
|
輸出:面試
1
2
3
4
|
ArithmeticException occured
finnaly occured
0
mian b= 3
|
結論: 若是try 中有異常, 則在異常語句處,跳轉到catch 捕獲的異常代碼塊, 執行完 catch 後,再執行 finally ,跳出 try{}catch{}finally{} ,繼續向下執行,不會去執行try中 後面的語句。算法