嵌套try-catch语句的替代方法

时间:2014-03-05 22:43:33

标签: c# exception-handling try-catch

我遇到了在catch块中需要try / catch的问题,但我读到这不是最佳做法。有没有更好的方法来解决这个问题?

        XmlDocument xmlDoc;
        try
        {
            xmlDoc = DocumentLoad(filepath);
        }
        catch (XmlException)
        {
            try
            {
                xmlDoc = DocumentLoadXml(filepath);
            }
            catch (Exception)
            {                    
                throw;
            }
        }

DocumentLoad(string filepath)使用XmlDocument.Load(),如果它抛出异常,我会尝试读取该文件,转义任何必要的&<>“',并使用XmlDocument.LoadXml()加载。但是这也可能会引发异常。

我不太热衷于首先尝试读取文件并查看是否存在无效字符,因为这可能不是必需的。

3 个答案:

答案 0 :(得分:3)

没关系,catch {throw;}是不必要的 - 这是默认行为:

    XmlDocument xmlDoc;
    try
    {
        xmlDoc = DocumentLoad(filepath);
    }
    catch (XmlException)
    {
        xmlDoc = DocumentLoadXml(filepath);  // if this throws an exception it will be rethrown
    }

但我很好奇为什么DocumentLoad会抛出异常而DocumentLoadXml却不会 - 你是否试图使该方法适用于文件路径和XML字符串?似乎有更好的方法来处理它。您是否可以只检查数据以查看哪种方法合适?

答案 1 :(得分:2)

你有什么理由不能这样做吗?

XmlDocument xmlDoc = null;
try
{
    xmlDoc = DocumentLoad(filepath);
}
catch (XmlException) {   }

if (xmlDoc == null)
    xmlDoc = DocumentLoadXml(filepath);

评论:

  • 第二次尝试/捕获被淘汰,因为你只是捕捉和投掷 - 如果你没有做任何事情,那么就不要抓住它

  • 你故意捕获并忽略第一个XmlException - 这很好,但这意味着我们只需要测试一个null xmlDoc并将其用作备用加载方法需要使用的指示符

答案 2 :(得分:0)

您可以移动两个块以使它们串联。如果第一个加载方法没有给你一个有效的文件,这只会尝试第二种加载方法。

    XmlDocument xmlDoc = null;
    try
    {
        xmlDoc = DocumentLoad(filepath);
    }
    catch (XmlException)
    {

    }

    if( xmlDoc == null ){
        xmlDoc = DocumentLoadXml(filepath);
    }
相关问题