c# - 我应该为失败的文件解析抛出什么异常?

标签 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);
}

在这种情况下我可以使用异常(exception)吗?我考虑过:

  • FormatException:问题不是很清楚,
  • 自定义异常:我对抛出的异常没有任何特殊处理,所以我宁愿避免使用自定义异常,尽管这始终是解决问题的一种方式。

最佳答案

FileFormatException应该没问题:

The exception that is thrown when an input file or a data stream that is supposed to conform to a certain file format specification is malformed.

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


如果您不想引用 WindowsBase,那么您可以针对您的格式创建自己的异常。基于 XmlReader.Read 抛出的 XmlException 这一事实.

关于c# - 我应该为失败的文件解析抛出什么异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26281600/

相关文章:

php - 使用 php ping 一个 ip,结果只有平均响应时间。

java - Jsoup.connect(url).get() 仅返回一半的代码

排序期间的 Java OutOfMemory

c# - SignInManager IsSignedIn 在 SignalR 集线器中返回 false

c# - 使用 nunit 测试测试内部函数的工作

python - 从 Simulink 模型获取模型拓扑

android - 文本输入布局错误 : Couldn't resolve resource @string/path_password_strike_through

c# - 了解异常 "An entity object cannot be referenced by multiple instances of IEntityChangeTracker."

c# - 如何实现二元方程的高斯消元法

c# - 中心内容 XAML