Is it ever good pratice to throw an exception in a finally block?

旧巷老猫 提交于 2019-12-12 18:52:28

问题


There's a good question Catch block is not being evaluated when exceptions are thrown from finallys that is discussing some of the sometimes unexpected results of throwing an exception in a finally block.

I can't think of any good reason why you would want to throw an exception in a finally block. If there was a previous exception, it would always be lost. I've always seen finally used to clean up in ways that should never throw an exception.

Can anyone explain when it would be appropriate to throw an exception in a finally block?


回答1:


try catch finally is pretty important construct. You can be sure that even if an exception is thrown, the code in finally block will be executed. It's very important in handling external resources to release them. Garbage collection won't do that for you. In finally part you shouldn't have return statements or throw exceptions. It's possible to do that, but it's a bad practice and can lead to unpredictable results.




回答2:


When you have a Exception thrown in finally it propagates up and most important stops at the point where the Exception is thrown, so the remainder of the finally would not be executed. Also if an exception has occurred in the try block it would have vanished and as the current one would be thrown from the finally block.

I am not able to think of any scenario as in where you would have a finally throwing up the Exception and then handling it at the caller level for a specific reason (there could be other ways of managing such logic), so you can at the caller level process further based on the Exception thrown.

All i can say is all the eyes that would read and try to follow the code later will have a healthy surprise.




回答3:


It is fine, well supported by .NET. The problem is catching the exception, that's a very poor practice. The odds that you'll properly restore program state are very low.



来源:https://stackoverflow.com/questions/12152926/is-it-ever-good-pratice-to-throw-an-exception-in-a-finally-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!