[OI] throw

throw 主要是用来抛出异常.

throw

可以直接向主程序 throw 一个东西,可以是各种数据类型,显示在界面上就是抛出的数据类型.

int main(){
	throw 1;
}
terminate called after throwing an instance of 'int'

--------------------------------
Process exited after 0.5906 seconds with return value 3

或者是自己定义的数据类型:

class hdk{};
int main(){
	throw hdk{};
}
terminate called after throwing an instance of 'hdk'

--------------------------------
Process exited after 0.5983 seconds with return value 3

可以看出返回值都是 \(3\). 因为抛出错误意味着程序非正常结束了.

try{throw}catch

因为这样抛出来不是很直观,因此 c++ 有一个专门的语句 try-throw

class hdk{};
int main(){
	try{
		if(true) throw hdk{};
	}
	catch(hdk){
		cout<<"Error"<<endl;
		exit(114514);
	}
}

我们把 throw 语句放进 try 里面,这样的话,throw 的东西不是直接输出到运行界面,而是扔到 catch 执行.

这个 catch 并不是逻辑判断,而是类型判断,只要 try 里扔出来的东西和它对上了就执行.

所以还有多行 catch 判断,直观点可以写成这样:

class DevidedByZero{};
class AnswerIsZero{};
int main(){
	while(1){
		int a,b;
		cin>>a>>b;
		try{
			if(b==0) throw DevidedByZero{};
			else if(a/b==0) throw AnswerIsZero{};
			else cout<<a/b<<endl;
		}
		catch(DevidedByZero){
			cout<<"Error: DevidedByZero"<<endl; 
		}
		catch(AnswerIsZero){
			cout<<"Error: AnswerIsZero"<<endl;
		}
	}
}
4 2
2
5 0
Error: DevidedByZero
0 5
Error: AnswerIsZero

或者使用 c++ 提供的标准错误流输出:

cerr<<"Error: DevidedByZero"<<endl; 

效果是一样的

posted @ 2024-06-19 21:24  HaneDaniko  阅读(24)  评论(1编辑  收藏  举报
/**/