> Whats the best way of handing exception of using?
There's no practical difference between the two options that you posted,
other than the presence of the "finally" block. You'd use "finally" for
the same reasons you'd use it otherwise: you have something that always
has to be done before exiting the try/catch/finally section, whether an
exception occurs or not.
Obviously, if the only reason you would have had a "finally" block before
is to dispose the "something" you've put in the "using" statement, then
you wouldn't need "finally". But otherwise, nothing has changed.
And next time, please indent any code you post. Thanks.
Pete
Robson Felix - 07 Mar 2008 19:38 GMT
I think you rather should put your using clause within the try catch. It
would make more sense, right?
>> Whats the best way of handing exception of using?
>
[quoted text clipped - 11 lines]
>
> Pete
Jon Skeet [C# MVP] - 07 Mar 2008 19:42 GMT
> I think you rather should put your using clause within the try catch. It
> would make more sense, right?
It depends on what you want to do in the catch block - if you need to
log the current state of the resource, for instance, you'd need to have
the catch block *inside* the using statement.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
parez - 07 Mar 2008 19:58 GMT
> > I think you rather should put your using clause within the try catch. It
> > would make more sense, right?
[quoted text clipped - 6 lines]
> Jon Skeet - <sk...@pobox.com>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
> World class .NET training in the UK:http://iterativetraining.co.uk
this is what i am planning to do.
I am planning use a resource which can throw exceptions..e.g I could
be using a streamwriter
using(StreamWriter sw = new StreamWriter())
and then i will do
sw.write(something)
Peter Duniho - 07 Mar 2008 19:45 GMT
> I think you rather should put your using clause within the try catch. It
> would make more sense, right?
It might. It might not. It really depends on what you're trying to do.
Without seeing of the rest of the code, it's impossible to say, as there's
no general-purpose rule that applies in all situations.
Pete
> Whats the best way of handing exception of using?
> Is it method 1 or method 2 or some other way
I'd either use
using (...)
{
try
{
}
catch (...)
{
}
}
or
try
{
using (...)
{
}
}
catch (...)
{
}
depending on whether or not I needed the resource from the using
statement within the catch block.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk