問題描述
在 Try Catch finally 塊中,finally 塊是否始終執(zhí)行,或者僅在 catch 塊不返回錯誤時(shí)執(zhí)行?
In a Try Catch Finally block, does the finally block always execute no matter what, or only if the catch block does not return an error?
我的印象是 finally 塊只有在 catch 塊通過且沒有錯誤的情況下才會執(zhí)行.如果catch塊因?yàn)殄e誤而被執(zhí)行,是不是應(yīng)該一起停止執(zhí)行并返回錯誤信息(如果有)?
I was under the impression that the finally block only executes if the catch block passes without errors. If the catch block is executed because of an error, shouldn't it stop execution all together and return the error message if any?
推薦答案
不僅 finally 塊會在 catch 塊之后執(zhí)行,try 甚至不需要捕獲任何異常來執(zhí)行 finally.以下是完全合法的代碼:
Not only will a finally block execute following a catch block, try does not even require that any exception be caught for the finally to execute. The following is perfectly legal code:
try
{
//do stuff
}
finally
{
//clean up
}
實(shí)際上,當(dāng) catch 塊包含以下內(nèi)容時(shí),我繼承了一些代碼中的 catch 塊:
I actually took out the catch blocks in some code I inherited when the catch block consisted of:
catch(Exception ex)
{
throw ex;
}
在這種情況下,所需要做的只是清理,所以我只留下了一個(gè) try{} 和 finally{} 塊,讓異常冒泡并保持其堆棧跟蹤完好無損.
In that case, all that was required was to clean up, so I left it with just a try{} and finally{} block and let exceptions bubble up with their stack trace intact.
這篇關(guān)于試著抓住最后的問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!