If I am using a try/catch/finally block where and how should I initialize variables? For example say I’m trying to use a FileStream . I want to catch any exceptions thrown while creating or using the stream. Then regardless of whether there were any problems or not I want to ensure any stream created is closed.
So I’d do something like this:
System.IO.FileStream fs;
try
{
fs = new System.IO.FileStream("C:\test.txt", System.IO.FileMode.Open);
//do something with the file stream
}
catch (Exception exp)
{
//handle exceptions
}
finally
{
//ERROR: "unassigned local variable fs"
if (fs != null)
{
fs.Close();
}
}
However this gives me an error in the finally block saying unassigned local variable fs. Yet, if I change the declaration of fs to System.IO.FileStream fs = null it works.
Why do I need to explicitly set fs to null? I’ve also tried declaring fs in the try block, but then I get the error The name fs does not exsist in the current context in finally block.
BTW: I know I could use a Using block, but the point of my question is to understand the correct usage of a try/catch/finally block.
See section 5.3 of the specification.
http://msdn.microsoft.com/en-us/library/aa691172(VS.71).aspx
With your try/catch/finally, the assignment of the
tryblock cannot be guaranteed when you attempt to access the object in thefinallyblock. As you have seen, you can meet the requirement by assigning an initial value to the variable (null, in this case).