异常
try { 被检查的语句 } catch(异常信息类型[变量名]) { 进行异常处理的语句 } |
#include <math.h> #include <iostream> using namespace std; double triangle(double a, double b, double c) { double area; double s = (a + b + c) / 2; if (a + b <= c || a + c <= b || b + c <= a) throw a; area = sqrt(s * (s - a) * (s - b) * (s - c)); return area; } int main() { double a, b, c; cin >> a >> b >> c; try { while (a > 0 && b > 0 && c > 0) { cout << triangle(a, b, c) << endl; cin >> a >> b >> c; } } catch (int) { cout << "a = " << a << " b = " << b << " c = " << c << ", that is not a trianle! "; } return 0; }
捕捉多个
#include <iostream> #include <string> using namespace std; void Demo1() { try { throw "hello"; } catch (char) { cout << "catch(char)" << endl; } catch (int) { cout << "catch(int)" << endl; } catch (double) { cout << "catch(double)" << endl; } catch (...) { cout << "catch(...)" << endl; // 捕获任意异常,或者叫匿名捕获异常 } } void Demo2() { throw "hello"; // throw string("D.T.Software"); } int main() { Demo1(); try { Demo2(); } catch (char*) { cout << "catch(char*)" << endl; } catch (string) { cout << "catch(string)" << endl; } }
自定义异常类
#include <exception> #include <iostream> using namespace std; class MyExecption : public exception { public: const char* what() const throw() { return "C++ Execption"; } }; int main() { try { throw MyExecption(); } catch (MyExecption& e) { cout << "My Exception caught" << endl; cout << e.what() << endl; } catch (exception& e) { cout << "other execption caught" << endl; } return 0; }
刚开始学比较疑惑的地方是下面这条语句为什么要在函数的后面加上 const throw() 这条语句,通过 这篇博客 了解到这样做的目的主要是限制 what 函数允许抛出什么样的异常,如果 throw() 中什么都不写的话就表示不允许抛出任何异常,这样做可以保证自定义异常类不会陷入死循环。
const char* what() const throw() { return "C++ Execption"; }
名字空间
命名空间的定义:
namespace namespace_name { // 代码声明 }
调用带有命名空间的函数或变量,需要在前面加上命名空间的名称
name::code; // code 可以使变量或函数
#include <iostream> using namespace std; namespace first_space { void func() { cout << "Inside first_space" << endl; } } // namespace first_space namespace second_space { void func() { cout << "Inside second_space" << endl; } } // namespace second_space using namespace second_space; int main() { func(); return 0; }