C++--内联函数--捕获异常

10.对于不包含循环的简单函数,建议用inline关键字声明为"inline内联函数",编译器将内联函数调用用其代码展开,称为“内联展开”,这样可以避免函数调用开销,提高程序执行效率

#include <iostream>
#include <cmath>
using namespace std;
inline double distance(double a,double b){ //内联函数
  return sqrt(a * a + b * b);
}
int main() {
  double k = 4,m = 1;
  //下面2行将产生同样的代码
  cout << distance (k,m) << endl;
  cout << sqrt(k * k + m* m) << endl; //运用内联函数直接用程序里的代码替换成函数调用
  return 0;
}

11.通过try-catch处理异常情况。把正常代码放在try块,在catch中捕获try块抛出的异常。

#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main(){
  int a,b;
  cout << "Type a number:";
  cin >> a;
  cout << endl;
  try {  //对try中代码块可能出出现的异常情况进行监测
    if(a > 100) throw 100;
    if(a < 10) throw 10; //抛出异常对象
    //throw a / 3;
    throw "hello";
  }
  catch (int result) {  //如果是整数类型就捕获异常
    cout<< "Result is:" << result << endl;
    b = result + 1;
    cout << "b contains: " << b << endl;
  }
//捕获字符串异常需要这样:
  catch(char * s){
  cout << "xixi" << string(s) << endl;  //这里要转化成c语言的字符串
  }
  
  cout << endl;



  char zero[] = "zero";
  char pair[] = "pair";
  char notprime[] = "not prime";
  char prime[] = "prime";
  try {  //根据不同情况抛出不同字符串
    if (a == 0) throw zero;
    if ((a / 2) * 2 == a) throw pair;
    for (int i = 3; i <= sqrt (a); i++){
      if ((a / i) * i == a) throw notprime;
    }
    throw prime;
  }
  catch (char *conclusion){
    cout<< "异常结果是:" << conclusion << endl;
  }
  catch (...) {  //抛出的异常与上述情况不匹配,表示所有的异常
    cout << "其他异常情况都在这里捕获" << endl;
  }
    cout << endl;
  retuen 0;
}
  


结果:输入一个数字14,被 字符串异常给捕获了,所以会输出"xixi",也会抛出异常hello,接下来执行下面的会捕获到pair异常。


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gaoxiaochan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值