我有一个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子句中?
谢谢
发布于 2011-04-20 19:56:31
代码的逻辑有些混乱,而且"serviceAvailable = false“的作用并不明显,因此很难给出详细的提示。异常处理的一般规则是,如果你真的知道如何处理它们以及如何解决问题,就捕获它们(而不是重新抛出)。如果你不知道这一点,或者程序将处于不能继续工作的状态,让异常通过,让你的程序崩溃。
在您的例子中,我可能会像这样构造代码:
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();你还应该看看"finally"-block。根据您的需求,您应该在这样的块中执行WriteBasicTemplate。但在你的情况下,我可能不会这么做。它更多的是用于资源清理或类似的东西。
https://stackoverflow.com/questions/5729690
复制相似问题