Can try catch be replaced by using?

Asked

Viewed 229 times

10

I always used the blocks try, catch and finally when programming in Java, and when I switched to C# I noticed that some codes exchange the try/catch for using.

Example:

using (FileStream fs = new FileStream("abc.txt", FileMode.Create))
{
    // Algum código...
}

2 answers

11


Yes, the most appropriate is to do with the using same. This code is equivalent to this:

{
    FileStream fs = new FileStream("abc.txt", FileMode.Create);
    try {
       // Algum código...
    } finally {
        if (fs != null)
            ((IDisposable)fs).Dispose();
    }
}

I put in the Github for future reference.

It’s more or less equivalent to try-resource java.

In some cases it may be more appropriate to do it manually, for example when you need a catch specific to that resource, or need to do something beyond the dispose() in the block of finally. In such cases it is important to make the appropriate provision in finally, as shown above.

Note that the using has nothing to do with try-catch, as asked, and yes to try-finally.

  • using is like an automatic Try, any instance that belongs to the interface idisposable it closes automatically at the end, I see that it is only a way to program faster and cleaner.

  • That’s right, it’s syntactic sugar.

5

You exchange only the try/finally for using. Wherever there is try/catch continues to be the same, because the using does not treat exception, it only ensures that an object will only exist within a scope - using {...} - defined.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.