Reputation:
As I know that Using statement has built in implementation of Dispose() and Try-Catch. So I want to know few things
Is it possible to log an exception inside using statement without using try-catch block , either inside or outside the statement. If not, then why its built in to the statement.
Nested or overuse of try-catch is not preferred, then why such model preferred to use.
using (some_resource)
{
try
{
}
catch
{
}
finally
{
//my exception logging mechanism
}
}
will become
try
{
try
{
}
catch
{
}
finally
{
//my exception logging mechanism
}
}
catch
{
}
finally
{
//some_resource.Dispose()
}
Upvotes: 1
Views: 1576
Reputation: 2590
Using compiles to Try{}Finally{}. See the following question: Does a C# using statement perform try/finally?
The reason for this is so that the resource will be disposed of regardless of if an exception is thrown. Resource disposal is the purpose of the using statement.
The correct implementation is:
using(Resource myresource = GetResource())
{
try
{}
catch(Exception e)
{ //Maybe log the exception here when it happens?
}
}
Upvotes: 1
Reputation: 1062790
A using
statement involves try
/finally
; there is no catch
. But frankly, your concern is overkill; multiply-nested and complex try
/catch
/finally
is "undesirable" because:
With using
, this isn't an issue; it makes the intent very clean, without adding complexity or concern.
I would just use:
using (some_resource) {
try {
// some code
} catch (Exception ex) {
LogIt(ex);
throw;
}
}
Upvotes: 5