对于失败的文件解析,我应该抛出什么异常?

Kil*_*zur 2 c# parsing exception

我有一个解析文件的方法.但是,这种解析可能会随时失败,具体取决于各种条件(例如,不太谨慎的用户使用该文件).

public string ParseDatFile(string datFile)
{
    string[] deezLines = File.ReadAllLines(datFile);

    // We're searching for an essential data inside the file.
    bool daEssentialDataFound = false;
    foreach (string datLine in deezLines)
    {
        if (datLine.Contains("daEssentialData"))
        {
            daEssentialDataFound = true;
            break;
        }
    }

    if (!daEssentialDataFound)
        throw new WhatShouldIThrowException("yo dood where's da essential data in " + datFile + "?");

    DoStuffWith(deezLines);
}
Run Code Online (Sandbox Code Playgroud)

我可以在这种情况下使用例外吗?我想过:

  • FormatException:不是很清楚这个问题,
  • 自定义异常:我没有对我抛出的异常进行任何特殊处理,所以我宁愿避免使用自定义异常,即使这总是一种解决问题的方法.

Gui*_*ume 6

FileFormatException应该没问题:

当输入文件或应该符合某种文件格式规范的数据流格式错误时引发的异常.

您可以选择提供uri和描述性错误消息.


如果您不想参考,WindowsBase那么您可以创建特定于您的格式的自己的例外.基于事实,有一个XmlException抛出XmlReader.Read.

  • 我不会用那个.这是在`WindowsBase`中定义的,因此这对于许多项目(控制台,ASP.Net ......)都不可用,并且您不希望仅为此类添加引用. (3认同)