在异常和返回值之间选择 [英] 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.
选项一
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.
这让我想知道,例如:
解析器在文件中发现未知字段,或者编码是
the parser finds unknown field in the file, or the encoding is wrong
会被视为异常情况吗?
推荐答案
想想解析错误是多么典型。如果是典型的 - 有利于返回值。例外应该用于不正常的事情。
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.
这篇关于在异常和返回值之间选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!