前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Cpp(六) 异常处理Exception

Cpp(六) 异常处理Exception

作者头像
Autooooooo
发布2020-11-09 10:42:39
8880
发布2020-11-09 10:42:39
举报
文章被收录于专栏:Coxhuang

C++ 异常处理

#1 环境

代码语言:javascript
复制
C++14
CMake 3.17
macOS 10.15.5
Clion

#2 开始

#2.1 格式

格式:

代码语言:javascript
复制
try{
   // 抛异常
    throw ExceptionType("xxx");
}catch( ExceptionType1 e1 ){ // ExceptionType1异常
    // 异常处理
}catch( ExceptionType2 e2 ){ // ExceptionType2异常
    // 异常处理
}catch( ExceptionTypeN eN ){ // ExceptionTypeN异常
    // 异常处理
}catch (exception e) { // 所有异常 
    // 异常处理
}

例子:

代码语言:javascript
复制
#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_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

发生数学下溢时,会抛出该异常

#2.3 自定义异常

代码语言:javascript
复制
#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;
}
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/10/09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C++ 异常处理
  • #1 环境
  • #2 开始
    • #2.1 格式
      • #2.2 异常类型
        • #2.3 自定义异常
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档