Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,
  • 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.
like image 802
Kilazur Avatar asked Dec 25 '22 03:12

Kilazur


1 Answers

FileFormatException should be fine :

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.


If you don't want to reference WindowsBase then you may create your own exception specific to your format. Based on the fact there is an XmlException thrown by XmlReader.Read.

like image 180
Guillaume Avatar answered Jan 10 '23 11:01

Guillaume