C++编程思想 第2卷 第1章 异常处理 标准异常

可以使用标准C++库中定义的异常
一般来说,使用标准异常类比用户自己定义异常类要方便快捷得多

所有的标准异常类归结到底都是从exception类诞生的,exception类的定义
在头文件<exception>中

通过excption::what()函数,可以从对象中得到它所保存的消息

//: C01:StdExcept.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.
// Derives an exception class from std::runtime_error.
#include <stdexcept>
#include <iostream>
using namespace std;

class MyError : public runtime_error {
public:
  MyError(const string& msg = "") : runtime_error(msg) {}
};

int main() {
  try {
    throw MyError("my message");
  } catch(MyError& x) {
    cout << x.what() << endl;
  }
  getchar();
} ///:~

尽管runtime_error的构造函数把消息保存在它的std::exception子对象中,
但是std::exceptioon并没有提供一个参数类型为std::string的构造函数

输入输出流异常类ios::failure从exception派生的,但没有子类 


输出
my message

猜你喜欢

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