Cpp(六) 异常处理Exception

C++ 异常处理

#1 环境

C++14
CMake 3.17
macOS 10.15.5
Clion

#2 开始

#2.1 格式

格式:

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;
}

在这里插入图片描述

#2.2 异常类型

在这里插入图片描述

异常类型描述
std::exception所有的异常
std::bad_allocnew异常
std::bad_castdynamic_cast异常
std::bad_exception无法预期的异常
std::bad_typeidtypeid异常
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发生数学下溢时,会抛出该异常

#2.3 自定义异常

#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;
}

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值