c++之try块和异常处理

异常处理:

            1)throw表达式:throw引发异常条件

            2)try块:try{...} catch(){...} catch(){..}模式,try块抛出异常,catch处理

            3)标准库异常类

 

throw表达式: 

   Sales_item item1, item2; 
     std::cin >> item1 >> item2; 
     // first check that item1 and item2 represent the same book 
     if (item1.same_isbn(item2)) { 
         std::cout << item1 + item2 << std::endl; 
         return 0; // indicate success 
     } else { 
         std::cerr << "Data must refer to same ISBN" 
                << std::endl; 
         return -1; // indicate failure 
     }


使用throw抛出异常:

// first check that data is for the same item 
     if (!item1.same_isbn(item2)) 
         throw runtime_error("Data must refer to same ISBN"); 
     // ok, if we're still here the ISBNs are the same 
     std::cout << item1 + item2 << std::endl;


问? throw使用的表达式是否可以自定义,即自定义函数来处理异常...

 

try块:

try { 
         program-statements 
     } catch (exception-specifier) { 
         handler-statements 
     } catch (exception-specifier) { 
         handler-statements 
     } //...

实例代码:

	try
	{
		int t_int = 13; 
		char* t_str = "fesdfe";

		if(t_int == 12)
			throw t_int;
		if(t_str != NULL)
			throw t_str;
	}
	catch(int i_param)
	{
		cout<<i_param<<endl;
	}	
	catch(char* str_param)
	{
		cout<<str_param<<endl;
	}

注意:一旦抛出异常,就是由接收到异常的catch结束运行,即在throw t_int抛出时,执行catch(int i_param)块后接收了try catch。

            根据throw出的条件,可以定义多个相应的catch

 

 

标准异常:

       assert()   //断言 条件为true不进行任何操作,为假抛出。

       其他标准异常

 


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值