• try,throw,catch


      基本结构:

    try{

    //语句块

    //. . .

    throw 形参;  //此处形参可以是基本数据类型,可以是字符串,可以是指针,可以是数组,也可以是类等。throw语句相当于return语句,不管在try语句块里还是try语句块中调用的函数中,一经throw,皆跳转至对应的catch子句并执行,然后继续向最后一个catch子句后的语句继续执行

    }

    catch(int *[ip]){}  // [ ]表示可要可不要,保留时一般需要用到传递过来的参数

    catch(int [i]){}

    catch(int value[]){}  //传递数组

    catch(MyClass &[tmp]){}

    catch(...){}  //throw的类型没在上边的catch子句中找到,最后统一处理

    throw 和 catch 的关系:

      类似函数的声明以及调用,分别设置形参和实参。catch语句可以只说明类型,也可以接收参数进一部操作

    throw 相当于 return :

      当try语句中执行throw语句时,根据类型进行匹配,若找到则执行catch子句,然后继续向下执行;若始终找不到对应的catch子句,程序调用库函数terminate终止程序:

     1 #include <iostream>
     2 using namespace std;
     3 void fun()
     4 {
     5     throw "a";
     6     cout<<"23333"<<endl;
     7 }
     8 int main(int argc, char** argv) {
     9     try
    10     {
    11         fun();
    12     }
    13     catch(...)
    14     {
    15         cout<<"error"<<endl;
    16     }
    17     fun();
    18     cout<<1+1<<endl;
    19     return 0;
    20 }

     1、C++中的new方法开辟空间失败时,抛出std::bad_alloc异常,使用try,catch语句捕捉

    1 try{
    2      int *p = new int;
    3      // ...
    4  }catch(const bad_alloc &e){
    5      cout<<"空间开辟失败";
    6  }

    2、理解和使用语句的层次性

     1 #include <iostream>
     2 using namespace std;
     3 void Base()
     4 {
     5     throw"base";//模拟开辟空间异常 
     6 }
     7 void fun()
     8 {
     9     try{
    10         Base();
    11     }catch(const char *s){
    12         throw"fun";
    13     }
    14  } 
    15  int main()
    16  {
    17      try{
    18          fun();
    19      }catch(const char *s){
    20          cout<<s;
    21      }
    22  }
    23 //output:fun
  • 相关阅读:
    【学习笔记】Hibernate关联映射(Y2-1-6)
    百度搜索排名API接口返回JSON数据格式
    HtmlAgilityPack 属性获取
    HtmlAgilityPack
    HighCharts实现双Y轴
    QQ在线客服配置
    项目管理者必知:适用于仪表盘项目的7个优秀JavaScript库
    极简Node教程-七天从小白变大神(二:中间件是核心)
    极简Node教程-七天从小白变大神(一:你需要Express)
    CSS滚动插件
  • 原文地址:https://www.cnblogs.com/guoyujiang/p/11594819.html
Copyright © 2020-2023  润新知