1

Say we create a IDisposable object, and we have a try-catch-finally block

var disposable= CreateIDisposable();
try{
  // do something with the disposable.
}catch(Exception e){
  // do something with the exception
}finally{
  disposable.Dispose();
}

How do I convert this to a using block?

If it were

var disposable= CreateIDisposable();
try{
  // do something with the disposable.
}finally{
  disposable.Dispose();
}

I would convert to

using(var disposable= CreateIDisposable()){
     // do something with the disposable.
}

How would I do this with the catch block?

try{
  using(var disposable= CreateIDisposable()){
     // do something with the disposable.
   }
}catch(Exception e){
  // do something with the exception
}
1
  • You have two choices, either using the code that you show (with the using statement inside the try clause, or with the entire try / catch within the using block. If no exception is thrown, then the code is nearly identical (the Dispose` call happens at the end, though the underlying assembly code will look different). If there is an exception, then, in either case, the catch clause would execute first and then the Dispose call on the way out the door. I'd call it a toss-up. Of course, your try / catch/ finally code is perfectly good as well Commented Feb 24, 2020 at 23:52

1 Answer 1

3

You're close. It's the other way around.

In reality, the CLR doesn't have try/catch/finally. It has try/catch, try/finally, and try/filter (that's what it does when the when clause is used on catch). try/catch/finally in C# is just a try/catch within the try block of a try/finally.

So if you expand that and convert the try/finally to using, you get this:

using (var disposable = CreateIDisposable())
{
    try
    {
        // do something with the disposable.
    }
    catch (Exception e)
    {
        // do something with the exception
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

@KristjanKica: I ran out of room in my comment on your question. But, I was going to say that this is the way I normally write these (though I have done try / catch / finally before
that makes more sense. My code would exceute "finally" before "catch"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.