2013-12-10 4 views
1

다음과 같은 방법으로 작성된 예외 처리 프로젝트가 있습니다.Java : 예외 처리기

상위 클래스에는 모든 예외 처리 논리가 있습니다. 호출 된 클래스는 예외를 throw하고 호출자 클래스는 적절한 논리를 처리합니다.

이제 호출 된 클래스에 직면 한 문제는 파일과 같이 다른 물건을 엽니 다. 이러한 파일은 예외시 닫히지 않습니다.

그래서이 경우 적절한 예외 처리 방법은 무엇이되어야합니다.

class A 
    { 
    private void createAdminClient() 
    { 

     try 
     { 
      B b = new B();   
       b.getClinetHandler(); 
     } 
     catch(CustomException1 e1) 
     { 
     } 
     catch(CustomException2 e1) 
     { 
     } 
     catch(CustomException3 e1) 
     { 
     } 
     catch(CustomException4 e1) 
     { 
     } 
    } 
} 

class B 
{ 
    ................ 
    ................ 

    getClinetHandler() throws Exception 
    { 
     --------------------------  
     ---- open a file---------- 
     -------------------------- 
     ----lines of code--------- 
     --------------------------  

     Exceptions can happen in these lines of code. 
     And closing file may not be called  

     --------------------------  
     ---- close those files---- 
     -------------------------- 

    } 

} 

답변

2

당신은 ... 시도 finally 블록에서 예외를 던질 수있는 코드를 래핑 할 수 있습니다

getClientHandler() throws Exception { 
    // Declare things which need to be closed here, setting them to null 
    try { 
     // Open things and do stuff which may throw exception 
    } finally { 
     // If the closable things aren't null close them 
    } 
} 

이 방법은 예외가 여전히 예외 처리기 최대 거품하지만 마지막 블록은 보장을 닫는 코드가 예외가 발생해도 여전히 호출됩니다.

0

블록을 사용하여 최종 작업을 완료하십시오. doc

로부터 예를

try 
    { 
     B b = new B();   
      b.getClinetHandler(); 
    } 
    catch(CustomException1 e1) 
    { 
    } 
    finally{ 
     // close files 
    } 

을 위해 마지막으로 항상 차단할 때 try 블록 종료를 실행합니다. 이렇게하면 예기치 않은 예외가 발생하더라도 finally 블록이 실행됩니다. 그러나 마침내 예외 처리 이외의 다른 용도로 유용합니다. 프로그래머는 return, continue 또는 break에 의해 실수로 우회 된 코드를 피할 수 있습니다. finally 블록에 정리 코드를 넣는 것은 예외가 예상되지 않는 경우에도 항상 좋은 방법입니다.

0

이것은 내가 그것을

try { 
    //What to try 
} catch (Exception e){ 
     //Catch it 
    } finally { 
        //Do finally after you catch exception 
     try { 
      writer.close(); //<--Close file 
     } catch (Exception EX3) {} 
    } 
0

(가 성공 또는 실패 여부에 관계없이) 후 처리 실행을 처리 할 finally 블록을 사용 할 방법이다. 그래서 같이 :

// Note: as Sean pointed out, the b variable is not visible to the finally if it 
// is declared within the try block, therefore it will be set up before we enter 
// the block. 
    B b = null; 

    try { 
     b = new B();   
     b.getClinetHandler(); 
    } 
    catch(CustomException1 e1) { 
    } // and other catch blocks as necessary... 
    finally{ 
     if(b != null) 
      b.closeFiles() // close files here 
    } 

finally 블록은 항상 관계없이 try 또는 catch 블록에서 심지어 당신이 경우 throw 또는 return 실행됩니다.

This answer은이 상황에서 finally 블록이 어떻게 작동하는지, 그리고 언제/어떻게 실행되는지에 대한 설명을 제공하며, 기본적으로 내가 방금 쓴 내용을 보여줍니다.

+1

이것은 원하는 것이 아닙니다. 닫을 수있는 객체는이 코드 블록에서 볼 수 없습니다. – Sean

+0

@Sean 궁극적으로 실행 후 파일을 닫는 방법을 묻는 것처럼 (getClientHandler 메서드에서) 원하는대로 생각합니다. 그러나 당신은 실제로'b' 변수가 보이지 않는다는 점에서 결함을 지적했습니다. –

+0

Hi Teeg, 내가 붙여 넣은 코드 스 니펫은 기본적으로 부모 클래스가 모든 예외 처리 로직을가집니다. 이 경우 closeFiles 및 기타 논리 처리 논리를 처리하는 다른 객체를 처리 할 때이 방법을 선택하면 부모에게 전달해야합니다. – Exploring