zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    核心API的使用(给定一个字符串,统计每个字符出现的次数)
    将博客搬至CSDN
    [DEBUG] python写文件时print漏掉整行数据
    [DEBUG] pyinstaller打包-命令行报错 pyinstaller failed to execute script 脚本名
    [DEBUG] springboot结合freemaker和js实现页面跳转和传值-踩坑记录
    724. 寻找数组的中心索引
    1010. 总持续时间可被 60 整除的歌曲
    27.移除元素
    [tensorflow] 入门day1-数据整理与展示
    [tensorflow] 安装
  • 原文地址:https://www.cnblogs.com/guoyujiang/p/11594819.html
Copyright © 2011-2022 走看看