C++异常处理

本文深入探讨了C++中的异常处理机制,包括使用try、catch、throw进行异常捕获和抛出的方法,以及如何利用C++标准库中的异常类如runtime_error和logic_error来增强代码的健壮性和可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一种是直接调用abort(),中断程序,不够灵活

 

另一种用try,catch的形式

即,

try{
...
if() throw ...
}
catch(Type){
...
}
catch(Type1){
...
}
..
catch(...){
...
}

多个catch捕获try模块的throw后的内容

具体来说,函数遇到throw,就会终端try模块的运行,根据throw的类型向下匹配catch内容,然后再catch之后执行,最后一个catch表示任何类型。没有遇到throw就try部分执行完了,跳过catch

对于函数部分的行为是,throw出的类型一路向下找catch,找不到就跳出函数再找,一层层,直到main也找不不到就一般默认调用abort()退出。

下面例子

#include <iostream>
#include <stdlib.h>
using namespace std;
 
double division(int a, int b)
{
   if( b == 0 )
   {
   	//	cout<<"input err"<<endl;
   		//abort();
      throw "Division by zero condition!";
   }
   return (a/b);
}
 
int Fun(int a,int b){
	return division(a,b);
	
}

int main ()
{
   int x = 50;
   int y = 0;
   double z = 0;
   while(1){
  
	cout<<"input x y to figure out x/y\n";
	cin>>x>>y; 
   try {
     z = Fun(x, y);
     cout << z << endl;
   }
   catch (const char * msg) {
     cerr << msg << endl;
   }
 	}
   return 0;
}

运行结果如下

 

 

此外,C++提供了stdexcept头文件提供了一些异常类

exception最常见的问题
runtime_error只有在运行时才能检测出的问题
range_error运行时错误:生成的结果超出了有意义的值域范围
overflow_error运行时错误:计算上溢
underflow_error运行时错误:计算下溢
logic_error程序逻辑错误
domain_error逻辑错误:参数对应的结果值不存在
invalid_argument逻辑错误:参数无效
length_error逻辑错误:试图创建一个超过该类型最大长度的对象
out_of_range逻辑错误:使用一个超出有效范围的值

  异常类只定义了一个名为what的成员函数,该函数没有任何参数,返回值是一个指向C风格字符串的const char*

以上的exception是一个基类,runtime_error与logic_error由它继承而来,接收string对象作为参数,提供what方法返回字符数据

 

以上代码可以改成

#include <iostream>
#include <stdlib.h>
#include <stdexcept>
using namespace std;
 
double division(int a, int b)
{
   if( b == 0 )
   {
   	//	cout<<"input err"<<endl;
   		//abort();
      //throw "Division by zero condition!";
      throw exception();//exception异常基类
     // throw runtime_error("y can't be 0");//runtime_error异常类
   }
   return (a/b);
}
 
int Fun(int a,int b){
	return division(a,b);
	
}

int main ()
{
   int x = 50;
   int y = 0;
   double z = 0;
   while(1){
  
	cout<<"input x y to figure out x/y\n";
	cin>>x>>y; 
   try {
     z = Fun(x, y);
     cout << z << endl;
   }
   catch (const char * msg) {//依次捕获几个类的异常
     cerr << msg << endl;
   }
	catch (const exception & err) {
     cerr << err.what() << endl;
   }
   catch (const runtime_error & err) {
     cerr << err.what() << endl;
   }
	}
   return 0;
}

分别抛出exception基类异常与runtime_error异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值