为什么Java在catch块内返回语句不起作用?

时间:2010-02-17 11:06:06

标签: java exception-handling return-value try-catch

为什么即使抛出异常,以下代码也总是返回true?

public boolean write (ArrayList<String> inputText, String locationToSave){

    try {           
        File fileDir = new File(locationToSave);
        Writer out = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(fileDir), "utf8"));

        int index = 0;
        int size = inputText.size();
        while (index < size) {
                    out.append(inputText.get(index));
                    out.append("\n");
                    index++;
                    }
        out.flush();
        out.close();

        return true;

   } catch (UnsupportedEncodingException e) {
        System.out.println("UnsupportedEncodingException is : \n" + e.getMessage());
        return false;
   } catch (IOException e) {
        System.out.println("IOException is : \n" + e.getMessage());
        return false;
   } catch (Exception e) {
        System.out.println("Exception is : \n" + e.getMessage());
        return false;
   }
}

Edition 01

这是我用来测试前面代码的代码:

 if (fileReader.write(fileReader.read(selectedFile), selectedSaveLocation)) {
        System.out.println("The file : " + selectedFile + " as been successfully"
        + "converted to : " + selectedSaveLocation );
    } else {
        System.out.println("The file : " + selectedFile + " failed to convert!" );
    }

4 个答案:

答案 0 :(得分:7)

我认为你没有看到你认为你所看到的。换句话说,我很确定它实际上是返回false,你应该检查调用代码。

例如,我将您的代码粘贴到一个新的Java控制台应用程序中,使其成为静态,并使用此正文编写了一个main方法:

System.out.println(write(null, null)); 

输出结果为:

Exception is : 
null
false

答案 1 :(得分:3)

它并不总是返回true。我创建了一个testproject,导致了IOException ......并且得到了错误!你的推理一定有错误。

答案 2 :(得分:1)

如果您在控制台中看到异常,并且返回值仍然为true,则检查异常类型。因为你捕获Exception,我猜它可能是一个未被检查的Throwable被触发。在这种情况下,您不会将标志设置为false。

我可能这样写:

public boolean write (Collection<String> inputText, String locationToSave)
{

    boolean isSuccessful = false;
    Writer out;

    try
    {

        File fileDir = new File(locationToSave);
        out = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(fileDir), "utf8"));

        for (String line : inputText)
        {
            out.append(inputText.get(index));
            out.append("\n");
        }

        isSuccessful = true;
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        cleanup(out);
    }    

    return isSuccessful;
}

private static void cleanup(Writer out)
{
    try
    {
        if (out != null)
        {
            out.flush();
            out.close();
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

答案 3 :(得分:1)

正如大家已经说过的那样,例外并不是你认为的例外。我猜这个方法

fileReader.read(selectedFile)

记录您在日志中看到的异常......

向我们展示这种方法的代码......并向我们展示例外......