简体   繁体   English

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

[英]What exception should I throw for a failed file parsing?

I have a method parsing a file. 我有一个解析文件的方法。 However, this parsing could fail anytime, depending on various conditions (not-so-cautious user playing with the file, for example). 但是,这种解析可能会随时失败,具体取决于各种条件(例如,不太谨慎的用户使用该文件)。

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

Is there an exception I could use in such a scenario? 我可以在这种情况下使用例外吗? I thought about: 我想过:

  • FormatException : not really clear about the issue, FormatException :不是很清楚这个问题,
  • Custom exception : I do not have any special treatment for the exception I'm throwing, so I'd rather avoid using a custom exception, even though that's always a way to settle things down. 自定义异常 :我没有对我抛出的异常进行任何特殊处理,所以我宁愿避免使用自定义异常,即使这总是一种解决问题的方法。

FileFormatException should be fine : 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. 当输入文件或应该符合某种文件格式规范的数据流格式错误时引发的异常。

You can optionally provide the uri and a descriptive error message. 您可以选择提供uri和描述性错误消息。


If you don't want to reference WindowsBase then you may create your own exception specific to your format. 如果您不想引用WindowsBase则可以创建特定于您的格式的自己的异常。 Based on the fact there is an XmlException thrown by XmlReader.Read . 根据事实, XmlReader.Read抛出了XmlException

I would throw a custom exception since that increases readability and allows to catch that specifc exception: 我会抛出一个自定义异常,因为这会增加可读性并允许捕获该特定异常:

public class InvalidFileFormatException : System.FormatException
{
    public InvalidFileFormatException(string exText) : base(exText) { }
}

// you could even provide an exception if a single line has an invalid format
public class SpecificLineErrorException : InvalidFileFormatException 
{
    public string Line { get; set; }
    public SpecificLineErrorException(string exText, string line) : base(exText) 
    {
        this.Line = line;
    }
}

Now your method can look like(also linqified it a little bit: 现在你的方法可以看起来像(也有点了解它:

public string ParseDatFile(string datFile)
{
    string[] deezLines = File.ReadAllLines(datFile);
    if(!deezLines.Any(l => l.Contains("daEssentialData")))
        throw new InvalidFileFormatException("yo dood where's da essential data in " + datFile + "?");
    DoStuffWith(deezLines);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM