2010-02-17 35 views
3

即使拋出異常,爲什麼下面的代碼總是返回true?爲什麼Java在catch塊內返回statment不工作?

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

如何你確認它被拋出? – Bozho 2010-02-17 11:13:00

+2

它返回false時,當我有一個錯誤,在調用此代碼時必須有另一個問題 – 2010-02-17 11:13:54

+0

@Bozho:以及我在終端中看到異常警告。 – 2010-02-17 11:39:30

回答

7

我不認爲你看到的是什麼,你認爲你看到了。換句話說,我很確定它實際上返回false,並且你應該檢查調用代碼。

例如,我貼你的代碼放到一個新的Java控制檯應用程序,使其靜態的,並寫了一個main方法這身搭配:

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

產量爲:

Exception is : 
null 
false 
3

它並不總是如此。我創建了一個測試項目,導致了一個IOException ...並且得到了錯誤!你的推理肯定有錯誤。

1

如果您在控制檯中發現異常,並且返回值仍然爲true,請檢查異常的類型。既然你捕獲異常,我猜測它可能是一個非檢查Throwable被觸發。在這種情況下,你永遠不會設置標誌爲假。

我可能會寫這樣說:

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(); 
    } 
} 
+0

我喜歡你的邏輯。但是我仍然不知道爲什麼當我打電話時,我得到的是「真正的」 – 2010-02-17 11:26:31

+0

@MAK:因爲你的代碼從不拋出異常 – mikek 2010-02-17 12:10:31

+0

它確實拋出異常......並且我在系統中看到它終端! – 2010-02-17 12:31:46

1

大家都已經說了,異常是不是你認爲它是一個。我猜的方法

fileReader.read(selectedFile) 

記錄你在日誌中看到異常......

向我們展示了該方法的代碼......並且還向我們展示了異常......

相關問題