Why Java return statment inside the catch block not working?

exception, java, return-value, try-catch

Solution

I don't think you're seeing what you think you're seeing. In other words, I'm pretty sure it's actually returning false, and that you should check the calling code.

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

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

The output was:

Exception is : 
null
false

Problem

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 I'm using 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!" ); } ```

Original source