views:

23

answers:

3

Is it good practice to close and dispose of resources before displaying error messages?

If you are catching errors and you display an error message in the same scope as resources such as database and file objects, then shouldn't these resources be closed and disposed of before the error message is displayed?

If you are waiting for these resources to drop out of scope then they will only do this once the error message dialog is closed. This means that a user could leave the error message on the screen for some time and in doing so keep a lock on some resources.

eg.

try { ... }
catch (Exception e) {
   // should close/dispose resources here
    ...
    ...
   MessageBox("Error");
}
A: 

You could try using the finally block.

http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx

Simmo
@Simmo: how does that address the issue? I am talking about waiting for someone to click OK on the Error message dialog. The finally block would only execute after this, wouldn't it?
Craig Johnston
Best practice would be to add to the finally block.
Simmo
+1  A: 

Preferably, don't display any UI in the catch block. Instead, dispose of the resources in the finally block, but return some value that indicates that an error occurred and have the calling method handle it, with UI if necessary.

A variation of that would be to dispose of the resources in the finally block and have the catch block rethrow the exception for the calling method to handle.

gkrogers
A: 

Better to be putting your resources in a

using( ) { } scope

or use RAII, so as they drop out of scope they are tidied up correctly before the messagebox is hit.

DanDan