Exceptions Vs Returns


/ Published in: C++
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #include <iostream>
  2. #include <stdexcept>
  3.  
  4. struct SpaceWaster {
  5. SpaceWaster(int l, bool b, SpaceWaster *p) : level(l), bad(b), prev(p) {}
  6. // we want the destructor to do something
  7. ~SpaceWaster() { prev = 0; }
  8. int checkLevel() { return level == 0;}
  9. int isBad() {return bad;}
  10. int level;
  11. bool bad;
  12. SpaceWaster *prev;
  13. };
  14.  
  15. void thrower(SpaceWaster *current) {
  16. if (current->checkLevel())
  17. {
  18. if (current->isBad())
  19. throw std::logic_error("some error message goes here\n");
  20. return;
  21. }
  22. SpaceWaster next(current->level - 1, current->isBad(), current);
  23. // typical exception-using code doesn't need error return values
  24. thrower(&next);
  25. thrower(&next);
  26. thrower(&next);
  27. return;
  28. }
  29.  
  30. char const* errorMsg;
  31.  
  32. char const* errorMsg;
  33.  
  34. int returner(SpaceWaster *current) {
  35. if (current->checkLevel())
  36. {
  37. if (current->isBad())
  38. {
  39. errorMsg = "some error message goes here\n:";
  40. return -1;
  41. }
  42. return 0;
  43. }
  44. SpaceWaster next(current->level - 1, current->isBad(), current);
  45. // typical exception-free code requires that return values be handled
  46. int result = returner(&next);
  47. if (result == 0)
  48. {
  49. result = returner(&next);
  50. }
  51. if (result == 0)
  52. {
  53. result = returner(&next);
  54. }
  55. return result;
  56. }
  57.  
  58. int main()
  59. {
  60. const int repeats = 1000;
  61. int returns = 0;
  62. int fails = 0;
  63.  
  64. for (int i = 0; i < repeats; ++i)
  65. {
  66. SpaceWaster first(10, (i%100) == 0, 0);
  67. #ifdef THROW
  68. try
  69. {
  70. thrower(&first);
  71. ++returns;
  72. }
  73. catch (std::exception &e)
  74. {
  75. ++fails;
  76. }
  77. #else
  78. if (returner(&first) == 0)
  79. {
  80. ++returns;
  81. }
  82. else
  83. {
  84. ++fails;
  85. }
  86. #endif
  87. }
  88. std::cout << fails << ":" << returns
  89. #ifdef THROW
  90. << " exceptions"
  91. #else
  92. << " returns"
  93. #endif
  94. << "\n";
  95. }
  96.  
  97. [Alpha:~] myork% g++ -DTHROW t.cpp
  98. [Alpha:~] myork% time ./a.out
  99. 10:990 exceptions
  100. 1.275u 0.001s 0:01.27 100.0% 0+0k 0+0io 0pf+0w
  101.  
  102.  
  103. [Alpha:~] myork% g++ t.cpp
  104. [Alpha:~] myork% time ./a.out
  105. 10:990 returns
  106. 1.325u 0.003s 0:01.33 99.2% 0+0k 0+0io 0pf+0w

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.