2011-04-20 73 views
0

我有一個xmlbuilder工具類調用幾個方法來建立一個XML文件如何處理異常正確

 public XMLBuilder(String searchVal) 
     { 
      this.searchVal = searchVal; 

      try 
      { 
       getData(); 
       returnedData = processDataInToOriginalFormat(); 
       WriteBasicTemplate(); 
      } 
      catch (WebException) 
      { 
       //If this is thrown then there was an error processing the HTTP request for MSO data. 
       //In this case then i should avoid writing the xml for concordance. 
       serviceAvailable = false; 
       MessageBox.Show("Could not connect to the required Service."); 

      } 
      catch (NoDataFoundException ndfe) 
      { 
       //propegate this back up the chain to the calling class 
       throw; 
      } 

processDataInToOriginalFormat();這是導致異常的類的方法,如果服務不可用的,我已經傳播了異常回到這裏來處理。我將嘗試設置一個布爾標誌來指示是否寫入一定數量的xml。如果該標誌爲假,則不寫。

但我忘了,異常停止程序流,現在我意識到這是不可能的,就像發生異常,其餘代碼不會恢復。我怎樣才能解決這個問題?只需將WriteBasicTemplate();調用添加到我的catch子句中?

感謝

回答

0

你的代碼的邏輯有點混亂,並因爲它並不清楚「服務現有=假」會做,很難給出詳細的提示。如果你真的知道如何處理它們以及如何解決這個問題,那麼處理異常的一般規則就是捕捉(而不是重新拋出)它們。我不知道,或者程序會處於無法繼續工作的狀態,讓異常通過並讓程序崩潰。

在你的情況我可能結構中的這樣的代碼:

 try 
     { 
      returnedData = processDataInToOriginalFormat(); 
      // put code here which should only be executed in 
      // case of no exception 
     } 
     catch (WebException) 
     { 
      // do what ever is required to handel the problem 
      MessageBox.Show("Could not connect to the required Service."); 
     } 
     // code which should be executed in every case 
     WriteBasicTemplate(); 

您也shoudl看看「終於」 - 塊。根據您的要求,您應該在這樣的塊中寫入基本模板。但我可能不會這樣做你的情況。它用於資源清理或類似的東西。

+0

當然要將異常傳播到更適合處理它的地方,您需要重新拋出? finally語句解決了我所有的問題,並且很抱歉讓邏輯難以遵循,我必須刪除業務數據。 – ricki 2011-04-20 12:04:31

+0

如果你完全沒有理解它,你不需要重新拋出它。 ;-)但是有時候人們必須抓住例外來決定是否可以處理。然後你必須重新拋出它當然。這是我試圖澄清的一點。 – Achim 2011-04-20 12:11:18