加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:52:05 所属栏目:Java 来源:网络整理
导读:为什么即使抛出异常,以下代码也始终返回true? public boolean write (ArrayListString inputText,String locationToSave){ try { File fileDir = new File(locationToSave); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream
为什么即使抛出异常,以下代码也始终返回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;
   }
}

第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!" );
    }

解决方法

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

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

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

输出是:

Exception is : 
null
false

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读