我应该把我自己的ArgumentOutOfRangeException或者让一个气泡从下面? [英] Should I throw my own ArgumentOutOfRangeException or let one bubble up from below?

查看:171
本文介绍了我应该把我自己的ArgumentOutOfRangeException或者让一个气泡从下面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个封装名单,其中一类;>

I have a class that wraps List<>

我已经通过索引方法GetValue:

I have GetValue by index method:

    public RenderedImageInfo GetValue(int index)
    {
        list[index].LastRetrieved = DateTime.Now;
        return list[index];
    }

如果用户请求的索引超出范围,这将引发ArgumentOutOfRangeException。

If the user requests an index that is out of range, this will throw an ArgumentOutOfRangeException .

我是不是应该让这种事发生或检查,并把我自己?即。

Should I just let this happen or check for it and throw my own? i.e.

    public RenderedImageInfo GetValue(int index)
    {
        if (index >= list.Count)
        {
            throw new ArgumentOutOfRangeException("index");
        }
        list[index].LastRetrieved = DateTime.Now;
        return list[index];
    }

在第一种情况下,用户必须从内部列表,它打破了用户不需要了解底层对象我的OOP目标的一个例外。

In the first scenario, the user would have an exception from the internal list, which breaks my OOP goal of the user not needing to know about the underlying objects.

而在第二种情况下,我觉得好像我加入冗余code。

But in the second scenario, I feel as though I am adding redundant code.

编辑:
而现在,我想起来了,怎么样一个第三方案,在那里我赶上了内部异常,修改它,然后重新抛出呢?


And now that I think of it, what about a 3rd scenario, where I catch the internal exception, modify it, and rethrow it?

推荐答案

您应该抛出自己的,为一对夫妇,原因如下:

You should throw your own, for a couple of reasons:

  1. 您可以明确地设置在构造函数中的相应的参数名称。这样一来,除了拥有的说法是超出范围的相应参数信息。
  2. (未成年人)的内部列表的异常将有一个无效的堆栈跟踪,只要你的用户而言。通过构造一个新的异常,你可以得到的堆栈跟踪显示你的方法是一个这是不恰当的,这将是更容易为你的用户的调试。

至于捕获和修改内部异常 - 我不会推荐这必然。如果异常是其中的额外信息将可能是有用的,你应该使用<一个href="http://msdn.microsoft.com/en-us/library/system.exception.innerexception.aspx">InnerException你的新的异常来propogate这些信息了。

As for catching and modifying the internal exception - I wouldn't recommend this, necessarily. If the exception is one where the extra information would potentially be useful, you should use the InnerException of your new exception to propogate this information up.

在这个例子中(ArgumentOutOfRangeException),事实上,有一个内部列表应尽可能的实现细节,而且也没有理由为你的用户看到这些信息。

In this example (ArgumentOutOfRangeException), the fact that there is an internal list should be kept as an implementation detail, and there's no reason for your user to see that information.

这篇关于我应该把我自己的ArgumentOutOfRangeException或者让一个气泡从下面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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