C++异常处理技术的使用方法可以描述为以下三步:
框定异常(try 语句)
在程序中,框定认为可能发生错误的语句序列,这些序列是异常发生的根源,如不框定
异常,则捕获不到任何异常。
定义异常处理(catch 语句)
将出现异常后的处理过程放在 catch 语句块中,当抛出异常时,就能因类型匹配而捕获异常。
抛弃异常(throw 语句)
在可能产生异常的语句中进行错误检测,如果有错误,就抛出异常。
框定异常和处理异常时在同一个函数中完成,抛出异常既可以和框定异常、处理异常在
同一个函数,也可以跨越函数。下面例子展示了异常处理的基本使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
#include "stdafx.h" #include <iostream> #include <string> using namespace std; int strToint(const string& str) { int num = 0; for (size_t i = 0; i < str.length(); i++) { if ((str.at(i) >= '0' && (str.at(i) <= '9'))) { num = num * 10 + str.at(i) - '0'; } else { throw str.at(i); } } return num; } int main() { string str; int iValue; cout << "please input a number string:\n"; cin >> str; try { iValue = strToint(str); if (iValue > 1000) throw iValue; } catch (char c) //如果里面代码要用到这个值,char 要定义变量 { cout << "input string includes illegal character:" << c << endl; //这里要用变量,不能用类型 iValue = -1; } catch (int) { cout << "number is too big:" << iValue << endl; } cout << iValue << endl; system("pause"); return 0; } |