Why doesn’t it work for Java to return a statement within a catch block?

Why does the following code always return true even if an exception is thrown?

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

This is the code I used to test the previous code:

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

Solution

I don't think you see what you think you see In other words, I'm pretty sure it actually returns false. You should check the calling code

For example, I paste your code into a new Java console application, make it static, and write a main method using this body:

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

The output is:

Exception is : 
null
false
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>