Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing between exception and return value

I have created a class that parses some document from file.

class Parser
{
  public Parse(string fileName)
  {
    ///
  }
}

Sometimes there can be parsing errors in that case parser has to return certain data. I have created special class for that.

class ParsingError
{
 // some data
}

How can I correctly deal with such errors. I have at least two options:

create my own exception or return value.

Option One

myParser.Parse(fileName, out error);

Option Two

try
{
  myParser.Parse(fileName)
}

catch(MyParsingException ex)
{
  // use ex.Error field
}

UPDATE

If I am not mistaken the ideology behind the exception is that it should deal with something exceptional, that is some situation that the method is not intended to deal with.

This leads me to wonder if for example:

the parser finds unknown field in the file, or the encoding is wrong

would that be considered an exceptional case?

like image 359
Captain Comic Avatar asked Mar 28 '11 14:03

Captain Comic


1 Answers

Think of how typical it is to have a parsing error. If it's typical - favor a return value. Exceptions should be used for things that are not normal.

like image 147
sharptooth Avatar answered Oct 23 '22 05:10

sharptooth