首页 \ 问答 \ TryFoo应该抛出异常吗?(Should TryFoo ever throw an exception?)

TryFoo应该抛出异常吗?(Should TryFoo ever throw an exception?)

.NET Framework中的一个常见模式是TryXXX模式(我不知道这是他们真正称之为的模式),其中被调用的方法尝试执行某些操作,如果成功则返回True ,如果操作失败则返回False 。 一个很好的例子是通用的Dictionary.TryGetValue方法。

这些方法的文档说他们不会抛出异常:该失败将在方法返回值中报告。 迄今为止都很好。

最近我遇到了两种不同的情况,实现TryXXX模式的.NET Framework方法会引发异常。 请参阅System.Random构造函数中的错误?Uri.TryCreate抛出UriFormatException? 了解详情。

在这两种情况下, TryXXX方法都会调用其他引发意外异常的方法,并且这些异常会被转义。 我的问题:这是否打破了不抛出异常的暗示合同?

换句话说,如果你正在写TryFoo ,你会保证异常无法逃避吗?

public bool TryFoo(string param, out FooThing foo)
{
    try
    {
        // do whatever
        return true;
    }
    catch
    {
        foo = null;
        return false;
    }
}

这很诱人,因为这样可以保证没有例外可以逃脱,从而履行隐含的合同。 但它是一个错误隐藏者。

根据我的经验,我的直觉表示这是一个非常糟糕的主意。 但是如果TryFoo允许一些异常逃逸,那么它真正的意思是“我不会抛出任何我知道如何处理的异常”,然后就抛出了合同“我不会抛出异常”的全部想法窗户。

那么,你有什么看法? TryFoo应该处理所有的异常,还是只处理所期望的异常? 你的推理是什么?


A common pattern in the .NET Framework is the TryXXX pattern (I don't know if that's what they really call it), in which the called method attempts to do something, returning True if it was successful, or False if the operation failed. A good example is the generic Dictionary.TryGetValue method.

Documentation for these methods say that they will not throw exceptions: that failure will be reported in the method return value. All good so far.

I recently encountered two different circumstances in which .NET Framework methods that implement the TryXXX pattern threw exceptions. See Bug in System.Random constructor? and Uri.TryCreate throws UriFormatException? for details.

In both cases, the TryXXX method called other methods that threw unexpected exceptions, and those exceptions escaped. My question: does this break the implied contract of not throwing exceptions?

Put another way, if you were writing TryFoo, would you guarantee that exceptions cannot escape, by writing it like this?

public bool TryFoo(string param, out FooThing foo)
{
    try
    {
        // do whatever
        return true;
    }
    catch
    {
        foo = null;
        return false;
    }
}

It's tempting, because that guarantees no exceptions will escape, thereby honoring the implied contract. But it's a bug hider.

My gut feeling, based on my experience, says that this is a really bad idea. But if TryFoo lets some exceptions escape, then what it's really saying is, "I won't throw any exceptions that I know how to handle," and then the whole idea of the contract "I won't throw exceptions" is thrown out the window.

So, what's your opinion? Should TryFoo handle all exceptions, or just those that it's expecting to happen? What's your reasoning?


原文:https://stackoverflow.com/questions/1166880
更新时间:2023-06-24 06:06

最满意答案

parser在解析时维护一个seen_actions集对象(在_parse_known_args方法中)。 在解析结束时,它会根据所需参数(具有required=True那些参数)检查此集合,并可能发出错误。 变化也用于互斥组。

但是这个变量在该函数之外是不可用的。 因此,缺少某种可以让你在parse_args动作中应用自己的测试的'钩子',你最好的选择就是测试默认值。 或者你可以看看sys.argv[1:]

默认的defaultNone 。 这对于这个目的很好,因为你的用户不能给这个值。 也就是说,没有字符串可以转换为None (至少不在任何常规type方法中)。

parser.add_argument('--foo') # default=None
...
if args.foo is None:
    # clearly foo has not been specified.
    args.foo = 'the real default'
else:
    # foo was specified
    pass

The parser maintains a seen_actions set object while parsing (in the _parse_known_args method). At the end of parsing it checks this set against the required arguments (ones with required=True), and may issue a error. A variation is also used with mutually exclusive groups.

But this variable is not available outside of that function. So short of some sort of 'hook' that lets you apply your own tests within the parse_args action, your best option is to test defaults. Or you can look at sys.argv[1:].

The default default is None. That is nice for this purpose because your user cannot give this value. That is, there's no string that converts to None (at least not in any of the normal type methods).

parser.add_argument('--foo') # default=None
...
if args.foo is None:
    # clearly foo has not been specified.
    args.foo = 'the real default'
else:
    # foo was specified
    pass

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。