2011-04-20 55 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