How to throw an exception in a using block with .NET 2.0?

I'm trying to use the used block more and more these days, when I have an object that implements IDisposable, but one thing I did not understand is how to catch the exception, as in the usual try / catch / finally ... any code samples to point me in the right direction?

Edit: The question has been modified after reading the answers. It was "How to throw an exception in a use block with .NET 2.0?" but I was really looking for a way to catch these exceptions inside the used block.


I am looking for more information on how to copy my own blocking block inside the block in use.

Edit: I wanted to avoid using try / catch / finally inside my used block, as shown in @Blair's figure. But maybe this is not a problem ...

Edit: @Blair, this is exactly what I was looking for, thanks for the detailed answer!

+4
source share
3 answers

I do not quite understand the question - you are making an exception, as usual. If MyThing implements IDisposable , then:

 using ( MyThing thing = new MyThing() ) { ... throw new ApplicationException("oops"); } 

And thing.Dispose will be called when you leave the block as an exception. If you want to combine try / catch / finally and usage, you can either nest them:

 try { ... using ( MyThing thing = new MyThing() ) { ... } ... } catch ( Exception e ) { .... } finally { .... } 

(Or put try / catch / finally when using):

 using ( MyThing thing = new MyThing() ) { ... try { ... } catch ( Exception e ) { .... } finally { .... } ... } // thing.Dispose is called now 

Or you can expand using and explicitly call Dispose in the finally block, as @Quarrelsome demonstrated, by adding the extra exception-handling or -recovery code that you need in finally (or catch ).

EDIT: in response to @Toran Billups, if you need to handle exceptions, except that you call your Dispose method, you will either have to use using , or try/catch/finally , or deploy using - I don't think there is another way accomplish what you want.

+7
source

Yes, there is nothing special about throwing exceptions into the use of blocks. Remember that the block used is basically converted to:

 IDisposable disposable = null; try { disposable = new WhateverYouWantedToMake(); } finally { disposable.Dispose() } 

Thus, you will have to fold your own trap if you want to catch something, but catch / throw is a completely separate issue with use. Finally, it is almost guaranteed to execute (save a fatal exception (for example, stackoverflow or outofmemory) or someone pulled the power from the PC).

+4
source

You need to have a try statement to catch the exception

Either you can use the try statement inside the use block, or use the use block in the try block

But you need to use a try block to catch any exceptions that occur

0
source

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


All Articles