using And Try Catch in harmony

  • Thread starter Thread starter parez
  • Start date Start date
P

parez

Whats the best way of handing exception of using?
Is it method 1 or method 2 or some other way
########## Method 1 ###########
using(something)
{
try
{
}
catch
{
}

}

########## Method 2 ###########
using(something)
{
try
{
}
catch
{
}
finally
{
}

}
 
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
 
parez said:
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.
 
I think you rather should put your using clause within the try catch. It
would make more sense, right?
 
Robson Felix said:
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.
 
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
 
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.


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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top