fearofawhackplanet
fearofawhackplanet

Reputation: 53456

Can you catch in a using block?

Can exceptions be caught inside a using block, and if so what is the syntax?

So, something like the following:

using (var creatingThing = new MyCreatingThing())
{
    creatingThing.CreateSomething();

    catch()
    {
        creatingThing.Rollback();
    }
}

Can this be done? Or do I need to write this code manually (ie without a using)?

Upvotes: 2

Views: 326

Answers (4)

James Curran
James Curran

Reputation: 103605

Note, the a using is really a try/finally under the covers, so it may be easier the code it that way:

MyCreatingThing creatingThing = null;
try
{
    creatingThing = new MyNCreatingThing())
    creatingThing.CreateSomething(); 
}    
catch() 
{ 
      Console.WriteLine("An Exception happened");
      if (creatingThing !=null)
          creatingThing.Rollback(); 
}
finally
{
      if (creatingThing !=null)
           creatingThing.Dispose(); 
}

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1503924

You can put a try/catch inside the using statement, or outside:

using (...)
{
    try
    {
        ...
    }
    catch
    {
        ...
    }
}

Or...

try
{
   using (...)
   {
       ...
   }
}
catch
{
    ...
}

However, you can't just put a catch block without a try block.

Choose the right one based on what whether you need to catch exceptions which are thrown by the resource acquisition expression, whether you want the resource to be disposed before your catch block is executed, and whether you need access to the resource variable within the catch block.

Upvotes: 15

Jeff Sternal
Jeff Sternal

Reputation: 48675

You cannot implicitly enlist in the try...finally block that the compiler generates (for the using statement). You have to add another try statement, which will be nested within the generated block:

using (var creatingThing = new MyCreatingThing())
{
    try
    {
        creatingThing.CreateSomething();
    }   
    catch
    {
        creatingThing.Rollback();
    }
}

Upvotes: 6

Hans Olsson
Hans Olsson

Reputation: 55059

Sure, just add the try inside the using:

using (var creatingThing = new MyCreatingThing())
{
    try
    {
    creatingThing.CreateSomething();
    }
    catch(Exception ex)
    {
        creatingThing.Rollback();
    }
}

Upvotes: 3

Related Questions