Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I initialize variables that will be used in a try/catch/finally block?

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.

like image 924
Eric Anastas Avatar asked Dec 08 '22 02:12

Eric Anastas


1 Answers

Assign fs = null;

  System.IO.FileStream fs = null;
    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();
        }
    }
like image 114
Michael Bazos Avatar answered May 22 '23 23:05

Michael Bazos