0

为什么我会收到错误消息: rawData 无法在 finally 块中解析?

在:

    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();
    }
}

谢谢

4

3 回答 3

1

rawDatatry块内声明。
该变量不存在于它之外。
特别是,如果try块在该行之前退出会发生什么?

您需要将声明移到try.

于 2013-10-07T14:33:10.613 回答
0

rawData对块不可见,finally因为它是在try块中声明的。

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

    } catch (FileNotFoundException e)
    {
        e.printStackTrace();
    } finally
    {
        if (rawData != null)
        {
            rawData.close();
        }
    }
}
于 2013-10-07T14:35:01.937 回答
0

你应该在 try/catch/finaly 块之外声明 rawData

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

    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    finally
    {
        rawData.close();
    }
}
于 2013-10-07T14:35:03.843 回答