C++_Primer05.sentence
语句
try 语句块和异常处理
C++ 中的异常处理:
- throw 表达式
- try-catch 语句块
- 一套异常类(exception class)
throw 表达式
throw 后紧跟一个表达式,表达式的类型就是抛出的异常类型
if (i != j){
throw runtime_error("Data must be in consistent");
}
类型 runtime_error 是标准异常类型的一种,定义在 stdexcept 头文件中
try 语句块
try {
// something
} catch (runtime_error err){
// something
}
函数报错时,首先搜索抛出该异常的函数,如果没有找到匹配的 catch 子句,终止该函数,并在调用该函数的函数中继续寻找,以此类推。如果最终没能找到任何匹配的 catch 字句,程序转到名为 terminate 的标准库函数。该函数的行为与系统有关,一般情况下,执行该函数将导致程序非正常退出。
标准异常
C++ 标准库定义了一组类,用于报告标准库函数遇到的问题,他们分别定义在4个头文件中:
- exception 头文件定义了最通用的异常类 exception,它只报告异常的发生,并不提供额外信息
- stdexcept 头文件定义了几种常用的异常类
- new 头文件定义了 bad_alloc 异常类型
- type_info 头文件定义了 bad_cast 异常类型
stdexcept 定义的异常类:
| 异常类 | 说明 |
|---|---|
| exception | 最常见的问题 |
| runtime_error | 只有在运行时才能检测出的问题 |
| range_error | 运行时错误:生成的结果超出了有意义的值域范围 |
| overflow_error | 运行时错误:计算上溢 |
| underflow_error | 运行时错误:计算下溢 |
| logic_error | 程序逻辑错误 |
| domain_error | 逻辑错误:参数对应的结果值不存在 |
| invalid_argument | 逻辑错误:无效参数 |
| length_error | 逻辑错误:试图创建一个超出该类型最大长度的对象 |
| out_of_range | 逻辑错误:使用一个超出有效范围的值 |
我们只能以默认初始化的方式初始化 exception, bad_alloc 和 bad_cast 对象,不允许为这些对象提供初始值;
其他异常类型的行为则恰好相反,应该使用 string 对象或 C 风格字符串初始化这些类型的对象,但是不允许使用默认初始化的方式。
异常类型只定义了一个名为 what 的成员函数,它没有任何参数,返回值是一个指向 C 风格字符串的 const char* 。该字符串的目的是提供关于异常的一些文本信息。
例子
#include <iostream>
#include <exception>
using namespace std;
int main () {
try
{
throw 1;
throw "error";
}
catch(const char *str)
{
cout << str << endl;
}
catch(int i)
{
cout << i << endl;
}
}
#include <iostream>
#include <exception>
using namespace std;
//可以自己定义Exception
class myexception: public exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
}myex;
int main () {
try
{
if(true) //如果,则抛出异常;
throw myex;
}
catch (exception& e)
{
cout << e.what() << endl;
}
return 0;
}
#include <iostream>
#include <exception>
using namespace std;
int main () {
try
{
int* myarray= new int[100000000000];
}
catch (exception& e)
{
cout << "Standard exception: " << e.what() << endl;
}
return 0;
}
output:
Standard exception: std::bad_alloc

浙公网安备 33010602011771号