在异常和返回值之间选择 [英] Choosing between exception and return value

查看:28
本文介绍了在异常和返回值之间选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个从文件中解析一些文档的类.

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.

这篇关于在异常和返回值之间选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆