Search code examples
finally

object cannot be resolved in finally block


Why do I get the error: rawData cannot be resoled in the finally block?

in:

    public void parseData(String fileName) throws IOException
{
    try
    {
        DataInputStream rawData = new DataInputStream(new FileInputStream(fileName));
        /* here I'm gonna do something*/

    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    finally
    {
        rawData.close();
    }
}

Thank you


Solution

  • You declared rawData inside the try block.
    The variable does not exist outside of it.
    In particular, what would happen if the try block exits before that line?

    You need to move the declaration outside the try.