处理异常的目的
在程序中出现非法操作时,可以防止程序崩溃。
异常的3个关键字
- try:try包住可能出现异常的程序块
- catch:捕捉并处理
- throw:抛出异常
程序实例
#include <iostream>
#include <string>using namespace std;int division()
{int a = 10;int b = 0;if (b == 0){//抛出异常throw "123";}return a / b;
}int main()
{try{division();}//根据类型捕捉异常//捕捉字符串遗产catch (const char* err){cout << err << endl;}//捕捉所有异常-直接受throw的异常catch (...){cout << "cause error" << endl;}
}
注意点
- 只有throw的异常才可以被catch。
- catch的类型要与抛出的相匹配。