try/catch之后的Java返回类型

try/catch之后的Java返回类型,java,android,return,try-catch,Java,Android,Return,Try Catch,我想从我创建的方法返回字符串类型的数据。Eclipse说需要在try-catch块之后指定返回类型。。。当我这样做时,Eclipse会告诉我需要将字符串数据声明为局部变量。。。这里出了什么问题 private String ReadData() { try { FileInputStream fis = null; InputStreamReader isr = null; String data = null; fis =

我想从我创建的方法返回字符串类型的数据。Eclipse说需要在try-catch块之后指定返回类型。。。当我这样做时,Eclipse会告诉我需要将字符串数据声明为局部变量。。。这里出了什么问题

private String ReadData() {
    try {
        FileInputStream fis = null;
        InputStreamReader isr = null;
        String data = null;
        fis = KVOContact.this.openFileInput("data.txt");
        isr = new InputStreamReader(fis);
        char[] inputBuffer = new char[fis.available()];
        isr.read(inputBuffer);
        data = new String(inputBuffer);
        isr.close();
        fis.close();

    } catch (IOException ioe) {
        Log.e("KVOContact", "IOError" + ioe);
    }
    return data;
}
数据变量仅限于try子句的范围。改为在try之外声明。

您在try块内声明数据。超出了那个街区的范围


您可以将声明移到try块之前,但我个人认为完全删除catch块并声明该方法可以抛出IOException可能更有意义。您还应该在finally块中关闭FileInputStream和InputStreamReader,以便在引发异常时不会让它们保持打开状态。

将return data语句放在try块内部


只有在try块内发生某些错误时才会调用catch,否则try将被执行,调用将返回到其起源地

您需要对代码进行一些更改:

private String ReadData() {
    String data = null;
    try {
        FileInputStream fis = null;
        InputStreamReader isr = null;        
        fis = KVOContact.this.openFileInput("data.txt");
        isr = new InputStreamReader(fis);
        char[] inputBuffer = new char[fis.available()];
        isr.read(inputBuffer);
        data = new String(inputBuffer);
        isr.close();
        fis.close();
    } catch (IOException ioe) {
        Log.e("KVOContact", "IOError" + ioe);
    }
    return data;
}
您需要声明一个字符串数据变量,该变量不在try块内,否则它将无法在try-catch块外看到。

是的,您还需要在catch部分使用return语句,请研究以下代码

private String ReadData() 
{
     try
     {
     .
     .
     . 
     return stringVariable;
     }
     catch ( IOException ioe )
     {
         Log.e("KVOContact", "IOError" + ioe);
         return NULL;
     }
}

好啊我不明白你的意思:删除catch块并声明该方法可以抛出IOException。。。不要?您需要始终捕获异常?私有字符串ReadData抛出IOExeption{}删除try-catch块并在调用方方法中捕获异常。@DennisvandenBrom:不,您不需要捕获异常-您可以声明该方法可能抛出异常,它只会冒泡。有关更多信息,请参阅。