• C++ 异常处理


    异常,让一个函数在遇到自己无法处理的问题时可以即时抛出,希望他到调用着直接或者间接的处理该异常。

    错误的处理依然是一件很困难的事情,C++的异常机制为程序员提供了一种处理错误的方式,使程序员可以更自然的方式处理错误。

     

    c++异常处理try catch特点:

    1. try catch可以嵌套使用

    2. 可以使用throw语句抛出异常

    3. 多个catch, 只有第一个匹配到的catch执行

    4. "..."作为兜底可以匹配所有异常, 应该放在最后catch, 方便其他catch分支匹配

     1 #include <iostream>
     2 #include <exception>
     3 
     4 using std::cout;
     5 using std::endl;
     6 
     7 class Test{
     8 public:
     9     Test(const std::string msg):_msg(msg) { } 
    10     std::string msg() { return _msg; }
    11 private:
    12     std::string _msg;
    13 };
    14 
    15 int main(){
    16     try{
    17         try{
    18             try{
    19                 //throw 4;
    20                 //throw "throw err msg";
    21                 throw 1.2;
    22                 //throw Test("test err");
    23             }   
    24             catch(int a){   //捕获int类型异常
    25                 cout << "catch " << a << endl;  
    26             }   
    27             catch(const char* msg){ //捕获char*类型
    28                 cout << "throw the old err" << endl;
    29                 throw ; //将异常原样抛出
    30             }   
    31             catch(Test &t){ //捕获Test类型异常
    32                 cout << "throw " << t.msg() << endl;
    33             }   
    34         }   
    35         catch(const char *msg){
    36             cout << "cat " << msg << endl;
    37         }   
    38     }   
    39     catch(...){ //"..."作为兜底可以捕获所有到异常, 一般放在最后一个catch
    40         cout << "other err" << endl;
    41     }
    42 
    43     return 0;
    44 }

     


     c++ 标准异常:

    http://www.cplusplus.com/reference/exception/exception/

  • 相关阅读:
    设计模式-装饰器模式
    自定义 RestTemplate 异常处理 (转)
    Jackson 高级应用
    Jackson 的 基本用法
    Jackson转换为Collection、Array
    Jackson中处理map中的null key 或者null value 及实体字段中的null value
    sed
    MySQL server has gone away 异常
    nl命令
    线程池
  • 原文地址:https://www.cnblogs.com/xudong-bupt/p/6344399.html
Copyright © 2020-2023  润新知