【问题标题】:Method with try catch and exception throws带有 try catch 和异常抛出的方法
【发布时间】:2012-10-23 22:01:25
【问题描述】:

所以我有以下方法:

template <class DT> //needs testing
DT& LinkedSortedArrays<DT>::find (const DT& key)
{
    list<SortedArray<DT>>::iterator it = SAList.begin();
    for( ; it != SAList.end(); ++it){
        try{
            if (it == SAList.begin() && key < (*it)[0]) throw Exception();
            return (*it).find(const_cast<DT&> (key));
        } catch (ArrayException e) {

        }
    }
    throw Exception();
}

我之前已经定义了 ExceptionArrayException 类。 (*it).find(const_cast&lt;DT&amp;&gt; (key)) 每次在当前正在搜索的特定 Array 类中找不到 key 时都会抛出 ArrayException。 SAListSTL List。代码编译得很好。但是我还没有在我的程序中尝试过。为什么?我需要有人确认或纠正我所做的以下假设:

  1. 每当if (it == SAList.begin() &amp;&amp; key &lt; (*it)[0]) throw Exception();抛出异常,就意味着它会抛出for循环之外,甚至是方法之外,对吧?
  2. 我几乎可以肯定最后一行throw Exception(); 会在方法外抛出异常。
  3. for循环的排列方式,不会跳过SAList的第一个元素吧?我的意思是,我在整个互联网上都看到了这个特定的代码,它用于迭代列表的所有元素,就好像它是标准的或完美的一样,但是...... ++it 正在扭曲我的大脑。帮忙?
  4. 我收到can't convert const int to int&amp; 的错误(因为(*it).find(const_cast&lt;DT&amp;&gt; (key)) 中的find() 不是属于LinkedSortedArrays 的那个,而是另一个需要DT& 变量和LinkedSortedArraysfind()具有 const DT&) 类型的参数,我发现一个可能的解决方案可能是将其写为const_cast&lt;DT&amp;&gt; (key)。我需要对此提出第二意见。

最后,我了解这是否不是一个具体问题,因此我会被否决和/或问题被关闭。我真的不知道还能去哪里问。 如果是我在错误的地方问的情况。我很抱歉。

【问题讨论】:

  • 为什么find 不通过 const 引用获取其参数?
  • 教授希望这样:/ 它基本上是属于另一个类的find,它与LinkedSortedArrays 一起构成了数据结构。

标签: c++ loops types try-catch


【解决方案1】:
  1. 是的,它将向上堆栈,直到找到合适的catch 处理程序。如果找不到这样的处理程序,程序将终止。

  2. 会的。

  3. 不,它不会,因为end 应该返回一个迭代器到最后一个,而不是最后一个元素。除非该容器的设计也很糟糕,但您必须查阅文档才能确定。

  4. 这是一个糟糕的设计,find 应该通过const 引用来获取它的参数。既然你不能,除非你想冒未定义行为的风险,否则你必须复制一份:

    DT nonconstkey = key;
    return it->find(nonconstkey);
    

【讨论】:

  • 您对ArrayExceptionException 之间的关系有何假设?
  • 是的,我知道,我非常清楚副本的需要。幸运的是,现在我只与ints 合作。所以暂时不用太头疼。
  • @MooingDuck 只是 Exception 不是 ArrayException 的子类。
  • 我忘了说,ArrayExceptionException 的子类
  • @Yokhen 很好,它不会改变答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
相关资源
最近更新 更多