Using or TryCatchFinally

  • Thread starter Thread starter K Viltersten
  • Start date Start date
K

K Viltersten

I can't decide whether i should deploy the
using statement or Try-Catch-Finally
statement.

I'd prefer using because it's more compact
and automagically disposes stuff.

On the other hand, i can't be sure that the
DB is working, so i might end up with an
ugly exception, which requires an explicit
try/catch to handle...

Suggestions?
 
K said:
I can't decide whether i should deploy the
using statement or Try-Catch-Finally statement.

I'd prefer using because it's more compact
and automagically disposes stuff.

On the other hand, i can't be sure that the DB is working, so i might
end up with an ugly exception, which requires an explicit try/catch to
handle...

Suggestions?

IDisposable resource = ...;
using (resource) {
...
}

is functionally equivalent to

IDisposable resource = ...;
try {
...
} finally {
if (resource != null)
resource.Dispose ();
}

(The compiler creates a temp variable to ensure that resource is not
changing.)

As you can see there is no catch block in the using statement
implementation.

So if you need a catch block then you have to create a catch block even
if you choose the using statement over a try-finally block.

Marvin
 
So if you need a catch block then you have to create
a catch block even if you choose the using statement
over a try-finally block.

Dang... :)

Thanks to both of you.
 
Back
Top