Exception detection in finally block

I am trying to write a Dispose method that has a potentian for exception.

Recognition is called in the try-finally pattern using the using statement:

 using(var widget = new Widget()) { widget.DoYourThing(); } 

The problem is that if an exception is thrown by the Dispose method, it replaces any exception that can be raised during the body of the using block. Usually this exception is less useful than the one that was thrown into the body.

I would like to write the Dispose method so that it swallows its own exceptions if there is already an exception. Something like the following would be ideal:

 protected virtual void Dispose(bool disposing) { try { this.Shutdown(); } catch(Exception) { this.Abort(); // Rethrow the exception if there is not one already in progress. if(!Runtime.IsHandlingException) { throw; } } } 

Is there anything that can provide this information?

+6
source share
2 answers

Is it really necessary for your Dispose method to throw an exception?

Perhaps you should create another deletion method with a different name and, if necessary, throw an exception. Then do Dispose by calling this other method wrapped in a try block that will catch an exception so that Dispose never throws.

+1
source

Source: https://habr.com/ru/post/895959/


All Articles