Why does Java return status inside catch block not working?

Why does the following code always return true, even when 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 that I use to verify 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!" );
    }
+3
source share
4 answers

I do not think that you see what you think you see. In other words, I'm sure that it actually returns false, and that you should check the calling code.

For example, I pasted your code into a new Java console application, made it static, and wrote the main method with this body:

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

The output was:

Exception is : 
null
false
+7
source

true. testproject, IOException... ! .

+3

, - , . 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();
    }
}
+1

, - , . ,

fileReader.read(selectedFile)

, ...

... ...

+1

Source: https://habr.com/ru/post/1733169/


All Articles