2010-02-17 3 views
3

예외가 throw 된 경우에도 다음 코드가 항상 true를 반환하는 이유는 무엇입니까?catch 블록 내부의 Java return statement가 작동하지 않는 이유는 무엇입니까?

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

+2

오류가 발생하면 여기에 false를 반환합니다.이 코드를 호출하는 동안 다른 문제가있을 수 있습니다. –

+0

@Bozho : 터미널에 예외 경고가 표시됩니다. –

답변

7

나는 당신이 당신을 어떻게 생각하는지보고 있다고 생각하지 않습니다는 보고 있습니다. 즉, 실제로 false를 반환하고 호출 코드를 확인해야합니다.

예를 들어, 나는 그것이 정적하게, 새로운 자바 콘솔 응용 프로그램에 코드를 붙여,이 몸 주요 방법을 썼다 :

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

출력했다 :

Exception is : 
null 
false 
3

그것을 항상 진실을 되 돌리는 것은 아닙니다. 나는 testproject를 만들었고, IOException을 발생 시켰고, false를 얻었습니다! 추론에 오류가 있어야합니다.

1

콘솔에 예외가 표시되고 반환 값이 계속 참이면 예외 유형을 확인하십시오. 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(); 
    } 
} 
+0

나는 당신의 논리를 좋아합니다. 그러나 여전히 내가 왜 그것을 "진실"하게하는지 모르겠다. –

+0

@MAK : 코드가 예외를 throw하지 않기 때문에. – mikek

+0

예외를 던져 버린다. 나는 시스템에서 그것을 본다. 터미널! –

1

, 예외가 당신이 생각하는 사람이 아니다. 나는 ...

우리에게이 방법의 코드를보기 ... 또한 우리에게 예외를 보여

fileReader.read(selectedFile) 

당신이 당신의 로그에서 볼 수있는 예외를 기록하는 방법을 ... 거라 생각