Samuel Neff
Samuel Neff

Reputation: 74899

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

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?

Upvotes: 2

Views: 379

Answers (3)

Hans Passant
Hans Passant

Reputation: 941218

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.

Upvotes: 1

V4Vendetta
V4Vendetta

Reputation: 38200

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.

Upvotes: 1

Peru
Peru

Reputation: 2971

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.

Upvotes: 1

Related Questions