top | item 37193967

(no title)

jammycakes | 2 years ago

Usually, no you don't. You only write a try ... catch or try ... finally block round the entire method body, from the point where you create the resources you may need to clean up to the point where you no longer need them. For example:

    var myFile = File.Open(filename);
    try {
        while ((var s = file.ReadLine()) != null) {
            var entity = ProcessLine(s);
            // do whatever you need to do to entity
        }
    }
    finally {
        myFile.Dispose();
    }
C# gives you the using keyword as syntactic sugar for this:

    using (var myFile = File.Open(filename)) {
        while ((var s = file.ReadLine()) != null) {
            ProcessLine(s);
            // do whatever you need to do to entity
        }
    }

discuss

order

catiopatio|2 years ago

That sounds incredibly ugly and painful.

jammycakes|2 years ago

It isn't in practice. Only a minority of methods actually need it.

It's certainly far, far better than having to add exactly the same check after every method call. Which is only what you need to do if you're working in a situation where exceptions are not an option.

turtles3|2 years ago

I'll add that C# also has using statements that dispose the object when the current scope exits (including if it exits due to an exception) this significantly cuts down on ugliness .