2012-07-03 2 views
2

예 : 파일을 열고 싶습니다. FileNotFoundException이 표시되면 잠시 후 다시 시도해야합니다. 어떻게하면 좋을까요? 또는 중첩 된 try/catch 블록을 사용해야합니까?예외가 throw 된 경우 Java는 계속 루프를 실행합니다.

예 :

public void openFile() { 
    File file = null; 
    try { 
     file = new <....> 
    } catch(FileNotFoundException e) { 
    } 
    return file; 
} 

답변

5

당신은 do { ... } while (file == null) 구조를 사용할 수 있습니다.

File file = null; 

do { 
    try { 
     file = new <....> 
    } catch(FileNotFoundException e) { 
     // Wait for some time. 
    } 
} while (file == null); 

return file; 
+0

덕분에, 그것은 :) 너무 쉽게했다 – Chris

+0

헤헤 .. 그래. 천만에요. – aioobe

1
파일이 결국 표시하지 않는 한 탈출 할 수있는 방법이 없기 때문에이 다소 위험한 방법이라고
public File openFile() { 
    File file = null; 
    while(true){ 
     try { 
      file = new <....> 
     } catch(FileNotFoundException e) { 
      //wait for sometime 
     } 
     if(file!=null){ 
       break; 
     } 
    } 
    return file; 
} 
3
public File openFile() { 
    File file = null; 
    while (file == null) { 
    try { 
     file = new <....> 
    } catch(FileNotFoundException e) { 
     // Thread.sleep(waitingTime) or what you want to do 
    } 
    } 
    return file; 
} 

참고. 당신은 예를 들어, 카운터를 추가하고 시도의 특정 숫자 후 줄 수 :

while (file == null) { 
    ... 
    if (tries++ > MAX_TRIES) { 
    break; 
    } 
} 
관련 문제