avatar

在做例外除錯的時候,我們有時候

介紹Finally

我們來看看Oracle是怎麼介紹Finally的:
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Finally它實用的地方在於可以讓程式開發上變得更簡潔,只要善用它的撰寫,你可以避免寫出return, continue, break…

Finally特性

  1. 要使用Finally的同時,必須要使用try
  2. 在正常的情況下,如果執行完try沒拋出任何exception時,依然會執行Finally block
  3. 即使在try裡面因為拋出異常或是return中止了程式的執行,依然會執行Finally block

例外除錯

1
2
3
4
5
6
7
8
9
try {
//Statements that may cause an exception
}
catch (error){
//Handling exception
}
finally {
//Statements to be executed
}

我們先以強行別的Java來當作介紹的範例
我們都知道在Java只要除以0就會拋出ArithmeticException的異常
你猜得到會輸出什麼嗎?

1
2
3
4
5
6
7
8
9
10
11
12
try{  
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("不可以除以0");
}
finally{
System.out.println("Finally");
}

System.out.println("在例外除錯外面");

答案:

1
2
3
不可以除以0
Finally
在例外除錯外面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class JavaFinally
{
public static void main(String args[])
{
System.out.println(JavaFinally.myMethod());
}
public static int myMethod()
{
try {
return 112;
}
finally {
System.out.println("This is Finally block");
System.out.println("Finally block ran even after return statement");
}
}
}

輸出:

1
2
3
This is Finally block
Finally block ran even after return statement
112

https://beginnersbook.com/2013/04/java-finally-block/
https://stackoverflow.com/questions/1158667/why-use-finally-in-try-catch

Also finally won’t be executed after a stackoverflow exception.


Comment