c++中的exception
std::exception
std::exception类定义了无参构造函数、拷贝构造函数、拷贝赋值运算符、一个虚析构函数和一个名为what的无参虚成员。其中what函数返回一个const char*,该指针指向一个以null结尾的字符数组,并且确保不会抛出任何异常,该字符串的目的是提供关于异常的一些文本信息。除析构函数外,其它函数均通过关键字noexcept说明此函数不会抛出异常。
例子:
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
#ifndef _MSC_VER
#define NOEXCEPT noexcept
#else
#define NOEXCEPT
#endif
struct ooops : std::exception {
public:
ooops(std::string data) {
d = data;
}
const char* what() const NOEXCEPT /*noexcept*/ override{ return d.c_str(); }
std::string d;
};
int main ()
{
try {
throw ooops("das");
} catch (std::exception& err) {
std::cout << err.what()
<< std::endl;
}
}
std::runtime_error
只有在运行时才会被检查出异常
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
#ifndef _MSC_VER
#define NOEXCEPT noexcept
#else
#define NOEXCEPT
#endif
int main ()
{
try {
throw std::runtime_error("dadsa");
} catch (std::exception& err) {
std::cout << err.what()
<< std::endl;
}
}
std::range_error
运行时错误,生成结果超出了有意义的值域范围
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
int main ()
{
throw std::range_error("dadsa");
}
std::overflow_error 和 std::underflow_error
overflow_error 上溢
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
int main ()
{
throw std::overflow_error("dadsa");
}
overflow_error 下溢
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
int main ()
{
throw std::underflow_error("dadsa");
}
logic_error
程序逻辑错误
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
int main ()
{
throw std::logic_error("dadsa");
}
std::domain_error
逻辑错误对应的结果值不存在
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
int main ()
{
throw std::domain_error("dadsa");
}
##std::invalid_argument
无效参数
#include <iostream>
int main ()
{
throw std::invalid_argument("dadsa");
}
std::length_error
逻辑错误,试图创建一个超出长度的对象
#include <iostream>
int main ()
{
throw std::length_error("dadsa");
}
std::out_of_range
逻辑错误使用一个超出有效范围的值
#include <iostream>
int main ()
{
throw std::out_of_range("dadsa");
}
C++ 异常处理 terminate函数使用
C++中处理异常的过程是这样的:在执行程序发生异常,可以不在本函数中处理,而是抛出一个错误信息,把它传递给上一级的函数来解决,上一级解决不了,再传给其上一级,由其上一级处理。如此逐级上传,直到最高一级还无法处理的话,运行系统会自动调用系统函数terminate,
#include <iostream>
void error()
{
std::cout << "error" << std::endl;
}
int main ()
{
std::set_terminate(error);
try {
throw std::logic_error("dada");
} catch (std::runtime_error& error1) {
} catch (std::length_error& error2) {
}
}