1.c++的异常处理

c++内置了异常处理的语法元素try…catch
—-try语句处理正常代码逻辑
—-catch语句处理异常情况
—-try语句中的异常由对应的catch语句处理

  1. try
  2. {
  3. double r = divide(1,0);
  4. }
  5. catch(...)
  6. {
  7. cout << "Divide by zero"<< endl;
  8. }

2.抛出异常

c++通过throw语句抛出异常信息

  1. double divide(double a,double b)
  2. {
  3. const double delta = 0.0000000000001;
  4. double ret = 0;
  5. if(!((-delta<b)&&(b<delta)))
  6. {
  7. ret = a / b;
  8. }
  9. else
  10. {
  11. throw 0; //产生0异常
  12. }
  13. return 0;
  14. }

3.c++异常处理分析

—-throw抛出的异常被catch处理
当前函数能够处理异常,程序继续往下执行
当前函数无法处理异常,则函数停止执行并返回

Slide5.PNG

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. double divide(double a, double b)
  5. {
  6. const double delta = 0.000000000000001;
  7. double ret = 0;
  8. if( !((-delta < b) && (b < delta)) )
  9. {
  10. ret = a / b;
  11. }
  12. else
  13. {
  14. throw 0;
  15. }
  16. return ret;
  17. }
  18. int main(int argc, char *argv[])
  19. {
  20. try
  21. {
  22. double r = divide(1, 0);
  23. cout << "r = " << r << endl;
  24. }
  25. catch(...)
  26. {
  27. cout << "Divided by zero..." << endl;
  28. }
  29. return 0;
  30. }

同一个try语句可以跟上多个catch
—-catch语句可以定义具体要定义的异常类型
—-不同类型的异常由不同的catch语句负责处理
—-try语句中可以抛出任何类型的异常
—-catch(…)用于处理所有类型的异常
—-任何异常都只能被捕获(catch)一次
Slide8.PNG

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. void Demo1()
  5. {
  6. try
  7. {
  8. throw 'c';
  9. }
  10. /*catch(...) //should be placed at the last place
  11. {
  12. }*/
  13. catch(char c)
  14. {
  15. cout << "catch(char c)" << endl;
  16. }
  17. catch(short c)
  18. {
  19. cout << "catch(short c)" << endl;
  20. }
  21. catch(double c)
  22. {
  23. cout << "catch(double c)" << endl;
  24. }
  25. catch(...)
  26. {
  27. cout << "catch(...)" << endl;
  28. }
  29. // catch(int c)
  30. ///{
  31. // cout << "catch(int c)" << endl;
  32. //}
  33. }
  34. void Demo2()
  35. {
  36. // throw "D.T.Software"; //type is const char*,can't be catched;type should be the same
  37. throw string("D.T.Software");
  38. }
  39. int main(int argc, char *argv[])
  40. {
  41. Demo1();
  42. try
  43. {
  44. Demo2();
  45. }
  46. catch(const char* s)
  47. {
  48. cout << "catch(const char *s)" << endl;
  49. }
  50. catch(string ss)
  51. {
  52. cout << "catch(string ss)" << endl;
  53. }
  54. return 0;
  55. }

小结:

1.c++中直接支持异常处理的概念
2.try…catch…是c++中异常处理的专用语句
3.try语句处理正常的代码逻辑,catch语句处理异常情况
4.同一个try语句可以跟上多个catch语句
5.异常处理必须严格匹配,不进行任何类型转换