【C++异常处理】

1.原理

  • 即运行时通知机制,在真正导致错误的语句执行之前并且异常发生的条件已经具备时,使用自定义的软件异常来代替错误,从而阻止异常的发生。

    参考 C++异常处理

2.实现

  • 关键字 try、throw、catch
try{
	...//省略
	throw()
}
catch(){
	...//省略
}
  • 三种用法
  1. 常见用法

  2. 规范的异常处理

函数类型 函数名(...) throw(类型)
{
	...//省略
	throw(...);
}

如类型可设为string或int从而保证抛出异常类型

  1. 异常和继承
class triangle:public exception:
{
	public:
	float a,b,c,d;
	triangle(){}
	triangle(float a1,float b1,float c1){
		a = a1;
		b = b1;
		c = c1;
	}
	void judgement() throw(exception){
		if((a+b)<c||(a+c)<b||(b+c)<a)
			throw exception("不是三角形")
	}
}

exception是C++类库的异常标准异常类
image


  • try可对应多个catch

  • 异常省略符 catch(...)

  • throw在catch中:①抛出新异常,②重新抛出异常

  • throw在函数中:函数抛出异常类型
    void example throw(int);

  • terminate() 记录错误,释放所有资源,调用abort()

  • unexpected() 记录错误并调用terminate()

posted @ 2021-08-26 17:17  西西果RuJ  阅读(60)  评论(0)    收藏  举报