Close and dispose of resources before displaying error messages?
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 开发者_StackOverflow中文版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");
}
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.
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.
You could try using the finally block.
http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
精彩评论