【C++异常】try cach

https://www.cnblogs.com/MrYuan/p/4800257.html

try/catch/throw处理异常

来源:https://www.runoob.com/cplusplus/cpp-exceptions-handling.html

处理异常:转移程序控制权

throw:抛出异常

catch:捕获异常

try:try 块中的代码标识将被激活的特定异常。它后面通常跟着一个或多个 catch 块。

//捕获异常,可以指定想要捕获的异常类型
//如果 try 块在不同的情境下会抛出不同的异常,这个时候可以尝试罗列多个 catch 语句,
//用于捕获不同类型的异常。
try{
   // 保护代码
}catch( ExceptionName e1 ){
   // catch 块
}catch( ExceptionName e2 ){
   // catch 块
}catch( ExceptionName eN ){
   // catch 块
}

//catch块处理任何类型的异常
try{
    //保护代码
}catch(...){
    //能处理任何异常的代码
}
//抛出异常
double division(int a, int b){
   if( b == 0 )//分母为0抛出异常
      throw "Division by zero condition!";
   return (a/b);
}

示例:

#include <iostream>
using namespace std; 
double division(int a, int b){
   if( b == 0 ) //抛出了const char*异常,捕获异常时,必须在catch块中使用const char*
      throw "Division by zero condition!";//一定要有
   return (a/b);
} 
int main (){
   int x = 50;
   int y = 0;
   double z = 0; 
   try {
     z = division(x, y);
     cout << z << endl;
   }catch (const char* msg) {
     cerr << msg << endl;//可以输出异常到屏幕
   } 
   return 0;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值