2013-12-10 58 views
1

我有一個項目,具有以下列方式編寫的異常處理:Java:異常處理程序

父類具有所有異常處理邏輯。被調用的類只是拋出異常並且調用者類以適當的邏輯處理。

現在我面臨被調用的類的問題打開不同的東西,例如一個文件。這些文件在異常時沒有關閉。

那麼在這種情況下應該如何處理異常處理的適當方式。

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

你可以用它可以在一個try ... 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 
    } 
} 

這樣異常仍冒泡的異常處理程序,但finally塊確保關閉代碼如果發生異常,仍然會被調用。

0

使用finally塊來完成最終的任務。例如

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

doc

的finally塊總是執行try塊退出時。這可確保即使發生意外異常也能執行finally塊。但是最後對於不僅僅是異常處理而言非常有用 - 它允許程序員避免由於返回,繼續或中斷而意外繞過清理代碼。清理代碼放在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塊總是執行,不管,即使你從trycatchthrowreturn

This answerfinally塊在這種情況下的工作原理以及何時/如何執行以及基本上進一步說明了我剛寫入的內容提供了非常好的解釋。

+1

這不是他們想要的。可關閉的對象在此代碼塊中不可見。 – Sean

+0

@Sean我認爲這是他們想要的,因爲他們最終要問如何在執行後關閉文件(在'getClientHandler'方法中)。但是你確實指出了一個缺陷,因爲'b'變量不可見,我會糾正它。 –

+0

您好Teeg,我粘貼的代碼片段,基本上父類具有所有的異常處理邏輯。如果在這種情況下選擇這種方式,那麼closeFiles和其他處理可關閉對象的邏輯必須轉到父 - 我不想要的。 – Exploring