异常处理Exception Handling
异常是指程序运行期间发生的不正常情况,如new无法获得所需内存、数组下标越界、运算溢出、除数为0、无效函数参数以及打开不存在的文件等。异常处理就是指对程序执行过程中发生的异常进行适当的处理,避免程序出现丢失数据活破坏系统运行等灾难性的后果。
其实异常处理可以用 if语句代替,但是会使代码难以维护。
举个例子
使用 if语句的代码:
// if statement #include <iostream> using namespace std; int main() { // Read two intergers cout << "Enter two integers: "; int number1, number2; cin >> number1 >> number2; if (number2 != 0) { cout << number1 << " / " << number2 << " is "; cout << (number1 / number2) << endl; } else { cout << "Divisor cannot be zero" << endl; } system("pause"); return 0; }
使用异常处理的代码:
// Exception Handling #include <iostream> using namespace std; int main() { // Read two intergers cout << "Enter two integers: "; int number1, number2; cin >> number1 >> number2; try { if (number2 == 0) throw number1; cout << number1 << " / " << number2 << " is " << (number1 / number2) << endl; } catch (int e) { cout << "Exception: an integer " << e << " cannot be divided by zero" << endl; } cout << "Execution continues ..." << endl; system("pause"); return 0; }
异常处理的模版:
try{ …… //try程序块 if err1 throw xx1 …… if err2 throw xx2 …… if errn throw xxn } catch(type1 arg){……} //异常类型1错误处理 catch(type2 arg){……} //异常类型2错误处理 catch(typem arg){……} //异常类型m错误处理
举个例子:
#include <iostream>
using namespace std;
void temperature(int t)
{
if (t == 100)
throw "feidian";
else if (t == 0)
throw "bingdian";
else
cout << "the temperature is ..." << t << endl;
}
int main()
{
try
{
temperature(10);
temperature(50);
temperature(100);
}
catch (const char *s)
{
cout << s << endl;
}
system("pause");
return 0;
}

转载请注明出处:https://www.cnblogs.com/stu-jyj3621

浙公网安备 33010602011771号