C++14
CMake 3.17
macOS 10.15.5
Clion
格式:
try{
// 抛异常
throw ExceptionType("xxx");
}catch( ExceptionType1 e1 ){ // ExceptionType1异常
// 异常处理
}catch( ExceptionType2 e2 ){ // ExceptionType2异常
// 异常处理
}catch( ExceptionTypeN eN ){ // ExceptionTypeN异常
// 异常处理
}catch (exception e) { // 所有异常
// 异常处理
}
例子:
#include <iostream>
#include <exception>
using namespace std;
int main() {
try {
throw length_error("length_error异常");
} catch (logic_error e) {
cout<<e.what()<<endl; // 打印异常信息
} catch (exception e) {
cout<<e.what()<<endl; // 打印异常信息
}
return 0;
}
异常类型 | 描述 |
---|---|
std::exception | 所有的异常 |
std::bad_alloc | new异常 |
std::bad_cast | dynamic_cast异常 |
std::bad_exception | 无法预期的异常 |
std::bad_typeid | typeid异常 |
std::logic_error | 读取代码来检测到的异常 |
std::domain_error | 使用了一个无效的数学域时,会抛出该异常 |
std::invalid_argument | 使用了无效的参数时,会抛出该异常 |
std::length_error | 创建了太长的 std::string 时,会抛出该异常 |
std::out_of_range | 通过方法抛出,例如 std::vector 和 std::bitset<>::operator |
std::runtime_error | 理论上不可以通过读取代码来检测到的异常 |
std::overflow_error | 发生数学上溢时,会抛出该异常 |
std::range_error | 存储超出范围的值时,会抛出该异常 |
std::underflow_error | 发生数学下溢时,会抛出该异常 |
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception
{
const char * what () const throw ()
{
return "Cpp Exception";
}
};
int main() {
std::cout << "Hello, Exception!" << std::endl;
try {
// throw length_error("length_error异常");
throw MyException(); // 主动抛出自定义异常
} catch (logic_error e) {
cout<<e.what()<<endl;
}catch (MyException& e) { // 捕获自定义异常
cout<<e.what()<<endl; // 打印异常信息
} catch (exception e) {
cout<<e.what()<<endl;
}
return 0;
}