在做例外除錯的時候,我們有時候
介紹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特性
- 要使用Finally的同時,必須要使用try
- 在正常的情況下,如果執行完try沒拋出任何exception時,依然會執行Finally block
- 即使在try裡面因為拋出異常或是return中止了程式的執行,依然會執行Finally block
例外除錯
1 | try { |
我們先以強行別的Java來當作介紹的範例
我們都知道在Java只要除以0就會拋出ArithmeticException的異常
你猜得到會輸出什麼嗎?
1 | try{ |
答案:
1 | 不可以除以0 |
1 | class JavaFinally |
輸出:
1 | This is Finally block |
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.