异常处理能够使程序处理一些特殊现象,并继续正确的执行。
C++抛出异常、捕获异常、处理异常:
#include <iostream>
using namespace std;
int main(){
cout << "输入两个整数:\n";
int number1, number2;
cin >> number1 >> number2;
/*
try----throw----catch模板
*/
try //try块正常情况下执行的代码
{
if (number2 == 0)
{
/*throw语句类似一个函数调用,但调用的不是一个函数,而是catch块*/
throw number1; //抛出异常,调用catch块代码
}
cout << number1 << " / " << number2 << " = " << (number1 / number2) << endl;
}
//catch块参数可以为任意类型,与抛出的异常值类型匹配
catch(int ex) //catch块参数获取抛出的异常值--捕获异常
{
//处理异常
cout << "异常:整数" << ex << "不能被0整除" << endl;
}
/*
如果你对异常对象的内容不感兴趣,那么可以忽略catch块参数
try
{
//...
}
catch(int)
{
cout << "Error occurred 错误发生。" << endl;
}
*/
return 0;
}
C++异常类:
#include <iostream>
#include <stdexcept>
using namespace std;
int quotient(int num1, int num2){
if (num2 == 0)
{
//通过传递一个异常的字符串来创建一个runtime_error对象
throw runtime_error("被除数不能为0");
}
return num1 / num2;
}
int main(){
cout << "输入两个整数:\n";
int number1, number2;
cin >> number1 >> number2;
try
{
int result = quotient(number1, number2);
cout << number1 << " / " << number2 << " = " << result << endl;
}
catch(runtime_error& ex) //捕获到一个runtime_error异常
{
cout << ex.what() << endl; //what函数返回一个描述异常的字符串
}
return 0;
}
来源:CSDN
作者:晓琴儿
链接:https://blog.csdn.net/Love_XiaoQinEr/article/details/104722460