fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <stdexcept>
  4.  
  5. /*
  6.  * Hilfskonstrukte
  7.  */
  8.  
  9. template <typename F>
  10. class CleanupHelper {
  11. public:
  12. CleanupHelper (F f) : m_f (std::move (f)) {}
  13. ~CleanupHelper () { m_f (); }
  14. private:
  15. F m_f;
  16. };
  17.  
  18. template <typename F>
  19. CleanupHelper<F> cleanup (F f) { return { std::move (f) }; }
  20.  
  21. /*
  22.  * Usercode
  23.  */
  24.  
  25. void tuwas () {
  26. std::cout << "Hole a\n";
  27. int a = 42; // a holen
  28. if (a == 0) throw std::runtime_error ("A initialization failed");
  29. auto cleanA = cleanup ([&] () { std::cout << "Cleaning A\n"; });
  30.  
  31. std::cout << "Hole b\n";
  32. int b = 3; // b holen
  33. if (b == 0) throw std::runtime_error ("B initialization failed");
  34. auto cleanB = cleanup ([&] () { std::cout << "Cleaning B\n"; });
  35.  
  36. std::cout << "Hole c\n";
  37. int c = 0; // c holen
  38. if (c == 0) throw std::runtime_error ("C initialization failed");
  39. auto cleanC = cleanup ([&] () { std::cout << "Cleaning C\n"; });
  40. }
  41.  
  42. int main() {
  43. try {
  44. tuwas ();
  45. } catch (std::exception& e) {
  46. std::cout << "Error: " << e.what () << std::endl;
  47. }
  48. return 0;
  49. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Hole a
Hole b
Hole c
Cleaning B
Cleaning A
Error: C initialization failed