Try catch can be replaced with using?

6

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

Example:

using (FileStream fs = new FileStream("abc.txt", FileMode.Create))
{
    // Algum código...
}
    
asked by anonymous 07.08.2016 / 03:19

2 answers

8

Yes, the best thing to do is using . 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();
    }
}

It roughly equates to try-resource veloper .

In some cases, it may be more appropriate to do it manually, for example when you need a specific%% of this feature, or need to do something other than catch in the dispose() block. In these cases it is important to make the appropriate provision in finally , as shown above.

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

    
07.08.2016 / 03:30
2

You only trade try/finally with using . Where try/catch remains the same, since using does not handle exception, it only guarantees that an object will only exist within a scope - using {...} - defined.

    
08.08.2016 / 17:46