c++ 异常处理 assert | try
#include <iostream> #include <cassert> using namespace std; int main() { int i = 1; assert(i == 65); cout << "Hello world" << endl; return 0; }
1 调试
2 我们可以利用它在某个程序里的关键假设不成立时,立刻停止该程序的执行并报错,从而避免更严重的错误
#include <iostream> #include<climits> using namespace std; unsigned long getFact(unsigned short num) throw (const char*); unsigned long getFact(unsigned short num) throw (const char*) { unsigned long sum = 1; unsigned long max = ULONG_MAX; for ( int i=1; i<=num; i++) { sum *= i; max /= i; } if ( max < 1) { throw "too big data!!! "; } else { return sum; } } int main() { try { unsigned short num = 13; unsigned long fac = getFact(num); cout << num << "!=" << fac << endl; } catch(const char *e) { cout << e << endl; } return 0; }