I am using some XmlReader and XmlWriter object to do some needed work on strings inside some try...catch blocks.
I know that using the notation using (XmlReader NewReader = XmlReader.Create(...)) is the prefered syntax, but I don't really like that so I am also appending finally blocks and executing NewReader.Close(); and NewWriter.Close();.
However, code analysis is complaining that these objects aren't being disposed, thus forcing me to somehow call Dispose() method.
The problem is that in these classes the Dispose() method is implemented explicitly, so I have to use ((IDisposable)(NewReader)).Dispose(); and ((IDisposable)(NewWriter)).Dispose();.
Are there any drawbacks to this technique?
There are good reasons for not using using:
When the lifetime of the object might need to survive longer than the current block
and there are poor reasons for avoiding using:
"I don't really like that"
Does the good reason apply to your code?
Please also note that a simple extension method would make the syntax nice and clean again.
The C# using statement will always call Dispose for you. It roughtly translates to the following:
XmlReader NewReader = XmlReader.Create(...);
try
{
// do stuff on NewReader
}
finally
{
((IDisposable)NewReader).Dispose();
}
So wrapping it in finally youself doesn't add any value. Although Close and Dispose are often equivalent, it is not always the case. Because of this FxCop is right, you should always call Dispose and when you do this (or let the using statement do this), there is no reason to call Close manually.
The using statement is really the preferred solution. It's idiomatic in C#. These classes implement IDisposable explicitly because they already provide a method that has closing semantics: Close. My bet is that Dispose calls Close, or vice-versa. But you shouldn't count on that, and should always call Dispose anyway.
In the end, all these are equivalent:
Use using, which is preferred;
Call Close on the finally block, and suppress the static analysis warnings or;
Call Dispose on the finally: ((IDisposable)NewReader).Dispose();
What is better, the using directive, or the dispose directive when finished with an object?
using(FileStream fileStream = new FileStream(
"logs/myapp.log",
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using(StreamReader streamReader = new StreamReader(fileStream))
{
this.textBoxLogs.Text = streamReader.ReadToEnd();
}
}
On the other hand, when I'm dealing with System.Net.Mail, I'm told I need to Dispose() of the object to release any stray locks.
Is there any consistent guidance? How do I tell what is more appropriate in a given situation for a given object?
The using statement (not directive) involves an implicit call to Dispose(), in a finally block. So there is no contradiction here. Can you link to that discussion?
The official definition of
using (x) { ... }
is
try ... finally if (x != null) x.Dispose(); }
What is better?
From a notational perspective, the using() { } block. Technically they are the same.
It's the same thing. Usage is simple, if you create the object and use it in only one method then use using. If you need to keep it alive beyond the method call then you have to use Dispose().
The runtime callable wrappers for COM objects don't have a Dispose() method.
There's no reason that I can think of to manually call Dispose(), other than in another implementation of Dispose() (for example in a class you've created that implements IDisposable) when you can wrap an object in a using block. The using block puts the creation and disposal of the object in a try/catch/finally block to pretty much gaurantee that the object will be disposed of correctly.
The compiler is more reliable than me. Or you. =)
MSDN documents the using statement and calls out where you can obtain the C# language specification where you can review section 8.13 "The using statement" (at least in the v4.0 reference it's 8.13) that gives a comprehensive explanation of the using statement and how to use it. The fifth paragraph gives the following:
A using statement is translated into
three parts: acquisition, usage, and
disposal. Usage of the resource is
implicitly enclosed in a try statement
that includes a finally clause. This
finally clause disposes of the
resource. If a null resource is
acquired, then no call to Dispose is
made, and no exception is thrown.
using(foo)
{
foo.DoStuff();
}
is just syntactic sugar for this:
try
{
foo.DoStuff();
}
finally
{
if(foo != null)
foo.Dispose();
}
So I'm not sure where the debate comes from. using blocks do call dispose. Most people prefer using blocks when possible as they are cleaner and clearer as to what is going on.
As long as the lifetime of the object is within a block of code, use using, if your object needs to be long lived, for example to be disposed after an asynchronous call you need to manually call Dispose.
A using block is way better than you of remembering the call to Dispose in all possible and impossible ways execution can leave a block of code.
using calls Dispose upon exit. using is better because it assures calling dispose.
using blocks automatically call Dispose() when the end of the block is reached.
There is one really important reason to use the "using statement" anywhere you can.
If the code that wrapped via using statement threw an exception, you could be sure that the "using object" would be disposed.
This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Which is better, and when: using statement or calling Dispose() on an IDisposable in C#?
When should I use “using” blocks in C#?
using a using if statement?
Properly, how will I use a using statement? I have a tutorial open and i do not understand it. And i can see more than 1 different ways to implement. Which is correct or favored way?
The using statement is for any object which implements IDisposable.
using (var my_object = new IDisposableObject ())
{
//do my_object code here.
} //once the program reaches here, it calls my_object.Dispose();
Generally, this is used for objects with connections that manually need to be handled (closed) when the program is finished with them. For example, open connections to files and to the database.
The using statement will call Dispose even if there is an error in the code so it is akin to calling the Dispose method in a finally block of the try catch statement.
Example/Tutorial
It's a shorter syntax to make sure that dispose is called:
using (File f = File.Open("..."))
{
}
is the same as
File f;
try
{
f = File.Open("...");
}
finally
{
f.Dispose();
}
There are 2 fundamental ways you can use the using statement. As extracted from using Directive (C#) from MSDN.
Create an alias for a namespace (a using alias).
Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (a using directive).
Just to expand on Kevin's answer, a using statement effectively wraps your object instantiation in a try/finally block calling the object Dispose() method in the finally section i.e.
using(myObject m = new myObjecyt())
{
// Code here
}
is the same as
myObject m = new myObjecyt()
try
{
// Code here
}
finally
{
m.Dispose();
}
this can be verified by checking the MSIL.
The "Using" keyword helps do a certain thing to be done safely and clearly in .net. This is propertly disposing of certain objects. You may have learned how in .Net we have garbage collection, which means for many object we don't have to care about them when we are done using them. Other object however need to have a method called on them called Dispose. The best practice is that whenever an object has a Dispose method, then we should call that method when we're done with that object.
(They typically handle unmanaged resources. This means that it's using memory or other computer parts that are outside the control of the .NET runtime. So, when garbage collection reaches the discarded .Net object, it is unable to propertly let go of these resources. This can cause memory leaks and all kinds of other problems. A good example is an ADO.NET Connection object. Repeatedly not Disposing of your connection objects can cause DB problems.)
The Using keyword is also tied to this "Dispose" method. It's more accurate to say that when an object has a Dispose method, we either (A.) call .Dispose when we're done with it, or (B.) put our code that uses that object within a Using block. The Using block does several things for you:
When the code moves out of the block, the important Dispose method is automatically called for you.
More importantly, if there is an error in the code block, the Dispose method will still be called. This is why the using block is really helpful. Otherwise you have to put in a lot of error handling code.
The key is that for many of these object that have a Dispose method, error handling is particularly imortant. For a lot our code we don't need error handling; the consequences of an error happening are not really a problem. But for these IDisposable objects errors are often a problem, maybe a big problem. So, .Net provides a syntax for busy developers to add the most basic error handling and move on. Always start off with a Using block at least; maybe later you'll move to fancier error handling, but at least you've got this basic safety.
Here's a good explanation of the Using keyword.
I've run ildasm to find that this:
using(Simple simp = new Simple())
{
Console.WriteLine("here");
}
generates IL code that is equivalent to this:
Simple simp = new Simple();
try
{
Console.WriteLine("here");
}
finally
{
if(simp != null)
{
simp.Dispose();
}
}
and the question is why the hell does it check null in the finally? The finally block will only be executed if the try block is executed, and the try block will only be executed if the Simple constructor succeeds (I.e. does not throw an exception), in which case simp will be non-null. (If there is some fear that some intervening steps might come between the Simple constructor and the beginning of the try block, then that would really be a problem because then an exception might be thrown that would prevent the finally block from executing at all.) So, why the hell?
Putting aside (please) the argument of whether the using statement is better than try-finally, I write my try-finally blocks as:
Simple simp = new Simple();
try
{
Console.WriteLine("here");
}
finally
{
simp.Dispose();
simp = null; // sanity-check in case I touch simp again
// because I don't rely on all classes
// necessarily throwing
// ObjectDisposedException
}
No, the finally block will ALWAYS be executed. You may not be getting the object from a new but from some other function that returns your object - and it might return NULL. using() is your friend!
dss539 was kind enough to suggest I include his note:
using(Simple simp = null)
is yet another reason that the expansion must check for null first.
using(Simple simp = null) is yet another reason that the expansion must check for null first.
MSDN on the using statement.
What I think is strange is that it doesn't expand to:
Simple simp = new Simple();
Simple __compilergeneratedtmpname = simp;
try
{
Console.WriteLine("here");
}
finally
{
if(__compilergeneratedtmpname != null)
{
__compilergeneratedtmpname.Dispose();
}
}
It appears that your comment:
"If there is some fear that some intervening steps might come between the Simple constructor and the beginning of the try block, then that would really be a problem because then an exception might be thrown that would prevent the finally block from executing at all."
is possibly dead on. See:
Atomicity & Asynchronous Exception Failures
I also want to note the issue(s) with WCF and using:
Avoiding Problems with the Using Statement and WCF Service Proxies which references:
Avoiding Problems with the Using Statement
The code must be translated this way to avoid possible NullReferenceException when disposing the object. As per C# language reference, the using statement accepts not only a local variable declaration as its first nonterminal resource_acquisition symbol, but any expression. Consider the following code:
DisposableType #object = null;
using(#object) {
// whatever
}
Clearly, unless null-conditional #object?.Dispose() in the finnaly block, an exception would ensue. The null check is superfluous only when the expression is of a non-nullable value type (non-nullable struct). And indeed, according to the aforementioned language reference it is absent in such case.
I have seen people say that it is bad form to use catch with no arguments, especially if that catch doesn't do anything:
StreamReader reader=new StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
catch // No args, so it will catch any exception
{}
reader.Close();
However, this is considered good form:
StreamReader reader=new StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
finally // Will execute despite any exception
{
reader.Close();
}
As far as I can tell, the only difference between putting cleanup code in a finally block and putting cleanup code after the try..catch blocks is if you have return statements in your try block (in that case, the cleanup code in finally will run, but code after the try..catch will not).
Otherwise, what's so special about finally?
The big difference is that try...catch will swallow the exception, hiding the fact that an error occurred. try..finally will run your cleanup code and then the exception will keep going, to be handled by something that knows what to do with it.
"Finally" is a statement of "Something you must always do to make sure program state is sane". As such, it's always good form to have one, if there's any possibility that exceptions may throw off the program state. The compiler also goes to great lengths to ensure that your Finally code is run.
"Catch" is a statement of "I can recover from this exception". You should only recover from exceptions you really can correct - catch without arguments says "Hey, I can recover from anything!", which is nearly always untrue.
If it were possible to recover from every exception, then it would really be a semantic quibble, about what you're declaring your intent to be. However, it's not, and almost certainly frames above yours will be better equipped to handle certain exceptions. As such, use finally, get your cleanup code run for free, but still let more knowledgeable handlers deal with the issue.
Because when that one single line throws an exception, you wouldn't know it.
With the first block of code, the exception will simply be absorbed, the program will continue to execute even when the state of the program might be wrong.
With the second block, the exception will be thrown and bubbles up but the reader.Close() is still guaranteed to run.
If an exception is not expected, then don't put a try..catch block just so, it'll be hard to debug later when the program went into a bad state and you don't have an idea why.
Finally is executed no matter what. So, if your try block was successful it will execute, if your try block fails, it will then execute the catch block, and then the finally block.
Also, it's better to try to use the following construct:
using (StreamReader reader=new StreamReader("myfile.txt"))
{
}
As the using statement is automatically wrapped in a try / finally and the stream will be automatically closed. (You will need to put a try / catch around the using statement if you want to actually catch the exception).
While the following 2 code blocks are equivalent, they are not equal.
try
{
int i = 1/0;
}
catch
{
reader.Close();
throw;
}
try
{
int i = 1/0;
}
finally
{
reader.Close();
}
'finally' is intention-revealing code. You declare to the compiler and to other programmers that this code needs to run no matter what.
if you have multiple catch blocks and you have cleanup code, you need finally. Without finally, you would be duplicating your cleanup code in each catch block. (DRY principle)
finally blocks are special. The CLR recognizes and treats code withing a finally block separately from catch blocks, and the CLR goes to great lengths to guarantee that a finally block will always execute. It's not just syntactic sugar from the compiler.
I agree with what seems to be the consensus here - an empty 'catch' is bad because it masks whatever exception might have occurred in the try block.
Also, from a readability standpoint, when I see a 'try' block I assume there will be a corresponding 'catch' statement. If you are only using a 'try' in order to ensure resources are de-allocated in the 'finally' block, you might consider the 'using' statement instead:
using (StreamReader reader = new StreamReader('myfile.txt'))
{
// do stuff here
} // reader.dispose() is called automatically
You can use the 'using' statement with any object that implements IDisposable. The object's dispose() method gets called automatically at the end of the block.
Use Try..Catch..Finally, if your method knows how to handle the exception locally. The Exception occurs in Try, Handled in Catch and after that clean up is done in Finally.
In case if your method doesn't know how to handle the exception but needs a cleanup once it has occurred use Try..Finally
By this the exception is propagated to the calling methods and handled if there are any suitable Catch statements in the calling methods.If there are no exception handlers in the current method or any of the calling methods then the application crashes.
By Try..Finally it is ensured that the local clean up is done before propagating the exception to the calling methods.
The try..finally block will still throw any exceptions that are raised. All finally does is ensure that the cleanup code is run before the exception is thrown.
The try..catch with an empty catch will completely consume any exception and hide the fact that it happened. The reader will be closed, but there's no telling if the correct thing happened. What if your intent was to write i to the file? In this case, you won't make it to that part of the code and myfile.txt will be empty. Do all of the downstream methods handle this properly? When you see the empty file, will you be able to correctly guess that it's empty because an exception was thrown? Better to throw the exception and let it be known that you're doing something wrong.
Another reason is the try..catch done like this is completely incorrect. What you are saying by doing this is, "No matter what happens, I can handle it." What about StackOverflowException, can you clean up after that? What about OutOfMemoryException? In general, you should only handle exceptions that you expect and know how to handle.
If you don't know what exception type to catch or what to do with it, there's no point in having a catch statement. You should just leave it for a higher-up caller that may have more information about the situation to know what to do.
You should still have a finally statement in there in case there is an exception, so that you can clean up resources before that exception is thrown to the caller.
From a readability perspective, it's more explicitly telling future code-readers "this stuff in here is important, it needs to be done no matter what happens." This is good.
Also, empty catch statements tend to have a certain "smell" to them. They might be a sign that developers aren't thinking through the various exceptions that can occur and how to handle them.
Finally is optional -- there's no reason to have a "Finally" block if there are no resources to clean up.
Taken from: here
Raising and catching exceptions should not routinely occur as part of the successful execution of a method. When developing class libraries, client code must be given the opportunity to test for an error condition before undertaking an operation that can result in an exception being raised. For example, System.IO.FileStream provides a CanRead property that can be checked prior to calling the Read method, preventing a potential exception being raised, as illustrated in the following code snippet:
Dim str As Stream = GetStream()
If (str.CanRead) Then
'code to read stream
End If
The decision of whether to check the state of an object prior to invoking a particular method that may raise an exception depends on the expected state of the object. If a FileStream object is created using a file path that should exist and a constructor that should return a file in read mode, checking the CanRead property is not necessary; the inability to read the FileStream would be a violation of the expected behavior of the method calls made, and an exception should be raised. In contrast, if a method is documented as returning a FileStream reference that may or may not be readable, checking the CanRead property before attempting to read data is advisable.
To illustrate the performance impact that using a "run until exception" coding technique can cause, the performance of a cast, which throws an InvalidCastException if the cast fails, is compared to the C# as operator, which returns nulls if a cast fails. The performance of the two techniques is identical for the case where the cast is valid (see Test 8.05), but for the case where the cast is invalid, and using a cast causes an exception, using a cast is 600 times slower than using the as operator (see Test 8.06). The high-performance impact of the exception-throwing technique includes the cost of allocating, throwing, and catching the exception and the cost of subsequent garbage collection of the exception object, which means the instantaneous impact of throwing an exception is not this high. As more exceptions are thrown, frequent garbage collection becomes an issue, so the overall impact of the frequent use of an exception- throwing coding technique will be similar to Test 8.05.
It's bad practice to add a catch clause just to rethrow the exception.
If you'll read C# for programmers you will understand, that the finally block was design to optimize an application and prevent memory leak.
The CLR does not completely eliminate leaks... memory leaks can occur if program inadvertently keep references to unwanted objects
For example when you open a file or database connection, your machine will allocate memory to cater that transaction, and that memory will be kept not unless the disposed or close command was executed. but if during transaction, an error was occurred, the proceeding command will be terminated not unless it was inside the try.. finally.. block.
catch was different from finally in the sense that, catch was design to give you way to handle/manage or interpret the error it self. Think of it as person who tells you "hey i caught some bad guys, what do you want me to do to them?"
while finally was designed to make sure that your resources was properly placed. Think of it of someone that whether or not there is some bad guys he will make sure that your property was still safe.
And you should allow those two to work together for good.
for example:
try
{
StreamReader reader=new StreamReader("myfile.txt");
//do other stuff
}
catch(Exception ex){
// Create log, or show notification
generic.Createlog("Error", ex.message);
}
finally // Will execute despite any exception
{
reader.Close();
}
With finally, you can clean up resources, even if your catch statement throws the exception up to the calling program. With your example containing the empty catch statement, there is little difference. However, if in your catch, you do some processing and throw the error, or even just don't even have a catch at all, the finally will still get run.
Well for one, it's bad practice to catch exceptions you don't bother to handle. Check out Chapter 5 about .Net Performance from Improving .NET Application Performance and Scalability. Side note, you should probably be loading the stream inside the try block, that way, you can catch the pertinent exception if it fails. Creating the stream outside the try block defeats its purpose.
Amongst probably many reasons, exceptions are very slow to execute. You can easily cripple your execution times if this happens a lot.
The problem with try/catch blocks that catch all exceptions is that your program is now in an indeterminate state if an unknown exception occurs. This goes completely against the fail fast rule - you don't want your program to continue if an exception occurs. The above try/catch would even catch OutOfMemoryExceptions, but that is definitely a state that your program will not run in.
Try/finally blocks allow you to execute clean up code while still failing fast. For most circumstances, you only want to catch all exceptions at the global level, so that you can log them, and then exit out.
The effective difference between your examples is negligible as long as no exceptions are thrown.
If, however, an exception is thrown while in the 'try' clause, the first example will swallow it completely. The second example will raise the exception to the next step up the call stack, so the difference in the stated examples is that one completely obscures any exceptions (first example), and the other (second example) retains exception information for potential later handling while still executing the content in the 'finally' clause.
If, for example, you were to put code in the 'catch' clause of the first example that threw an exception (either the one that was initially raised, or a new one), the reader cleanup code would never execute. Finally executes regardless of what happens in the 'catch' clause.
So, the main difference between 'catch' and 'finally' is that the contents of the 'finally' block (with a few rare exceptions) can be considered guaranteed to execute, even in the face of an unexpected exception, while any code following a 'catch' clause (but outside a 'finally' clause) would not carry such a guaranty.
Incidentally, Stream and StreamReader both implement IDisposable, and can be wrapped in a 'using' block. 'Using' blocks are the semantic equivalent of try/finally (no 'catch'), so your example could be more tersely expressed as:
using (StreamReader reader = new StreamReader("myfile.txt"))
{
int i = 5 / 0;
}
...which will close and dispose of the StreamReader instance when it goes out of scope.
Hope this helps.
try {…} catch{} is not always bad. It's not a common pattern, but I do tend to use it when I need to shutdown resources no matter what, like closing a (possibly) open sockets at the end of a thread.