C++编程思想 第2卷 第1章 异常处理 异常匹配

一个异常被抛出以后,异常处理系统将按照在源代码中出现的顺序查找
最近的异常处理器
一旦找到匹配的异常处理器,就认为该异常已经被处理了而不再继续查找
下去

匹配一个异常并不要求异常与其处理器之间完全相关
一个对象或者是指向派生类对象的引用都会与其基类处理器匹配
 

//: C01:Autoexcp.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// No matching conversions.
#include <iostream>
using namespace std;

class Except1 {};

class Except2 {
public:
  Except2(const Except1&) {}
};

void f() { throw Except1(); }

int main() {
  try { f();
  } catch(Except2&) {
    cout << "inside catch(Except2)" << endl;
  } catch(Except1&) {
    cout << "inside catch(Except1)" << endl;
  }
  getchar();
} ///:~

尽管读者可能会认为,通过使用转换构造函数将一个Except1对象转换成
一个Except2对象,可以使得第一个异常处理器被匹配

输出
inside catch(Except1)

基类的异常处理器怎样能够捕获派生类异常

//: C01:Basexcpt.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Exception hierarchies.
#include <iostream>
using namespace std;

class X {
public:
  class Trouble {};
  class Small : public Trouble {};
  class Big : public Trouble {};
  void f() { throw Big(); }
};

int main() {
  X x;
  try {
    x.f();
  } catch(X::Trouble&) {
    cout << "caught Trouble" << endl;
  // Hidden by previous handler:
  } catch(X::Small&) {
    cout << "caught Small Trouble" << endl;
  } catch(X::Big&) {
    cout << "caught Big Trouble" << endl;
  }
  getchar();
} ///:~

在这里,异常处理机制总是将Trouble对象,或派生自Trouble的任何对象
通过共有继承,匹配到第一个异常处理器

通过引用来捕获异常的,尽管对这些类而言这一点并不重要,因为派生类
中没有附加的成员,而且异常处理器中也没有参数标识符

输出
caught Trouble
 

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81569064