异常和返回值之间进行选择 [英] 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 should 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
}
更新
如果我不mustaken异常背后的idelogy是一些特殊情况是某些情况下,该方法不适合处理。所以我想如果例如
解析器发现未知领域的文件中,或者编码是错误的是特殊情况?
If I am not mustaken the idelogy behind the exception is that something exceptional that is some situation that the method is not intended to deal with. So I wonder if for example the parser finds unknown field in the file, or the encoding is wrong is that exceptional case?
推荐答案
想想这是多么典型的有一个解析错误。如果这是典型的 - 有利于返回值。异常应该用于东西都是不正常的。
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屋!