在异常和返回值之间选择
我创建了一个从文件中解析一些文档的类.
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.
选项一
myParser.Parse(fileName, out error);
方案二
try
{
myParser.Parse(fileName)
}
catch(MyParsingException ex)
{
// use ex.Error field
}
更新
如果我没记错的话,异常背后的思想是它应该处理一些异常的东西,那是一些方法不打算处理的情况.
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.
这让我想知道例如:
解析器在文件中发现未知字段,或者编码错误
这会被视为特例吗?
想想解析错误是多么典型.如果它是典型的 - 支持返回值.异常应该用于不正常的事情.
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.