Search code examples
c#databasetry-catchusing-statement

C#: "using" directive and try/catch block


I know how to use try/catch block in case of database calls and know how to use "using" directive in context of using try/finally construction as well.

But, can I mix them? I mean when I use "using" directive can I use try/catch construction as well because I still need to handle possible errors?


Solution

  • Of course you can do it:

    using (var con = new SomeConnection()) {
        try {
            // do some stuff
        }
        catch (SomeException ex) {
            // error handling
        }
    }
    

    using is translated by the compiler into a try..finally, so it's not very different from nesting a try..catch inside a try..finally.