Advertisement
anechka_ne_plach

try weak

Oct 14th, 2021
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. #include <exception>
  2. #include <stdexcept>
  3. #include <cstring>
  4. #include <cassert>
  5. #include <string>
  6.  
  7. template <class T>
  8. class Try {
  9. public:
  10.     Try() {
  11.     }
  12.     Try(T value) : value(value), empty(false) {
  13.     }
  14.     Try(std::exception& e) {
  15.         try {
  16.             throw e;
  17.         } catch(...) {
  18.             eptr = std::current_exception();
  19.         }
  20.     }
  21.     const T& Value() {
  22.         if (eptr) {
  23.             std::rethrow_exception(eptr);
  24.         } else if (empty) {
  25.             throw std::runtime_error("Object is empty");
  26.         }
  27.         return value;
  28.     }
  29.     virtual void Throw() {
  30.         if (eptr) {
  31.             std::rethrow_exception(eptr);
  32.         } else {
  33.             throw std::runtime_error("No exception");
  34.         }
  35.     }
  36.     bool IsFailed() {
  37.         if (eptr) {
  38.             return true;
  39.         } else {
  40.             return false;
  41.         }
  42.     }
  43. protected:
  44.     bool empty = true;
  45.     T value{};
  46.     std::exception_ptr eptr;
  47. };
  48.  
  49. template <>
  50. class Try<void> {
  51. public:
  52.     Try() {
  53.     }
  54.     Try(std::exception& e) {
  55.         try {
  56.             throw e;
  57.         } catch(...) {
  58.             eptr = std::current_exception();
  59.         }
  60.     }
  61.     virtual void Throw() {
  62.         if (eptr) {
  63.             std::rethrow_exception(eptr);
  64.         } else {
  65.             throw std::runtime_error("No exception");
  66.         }
  67.     }
  68.     bool IsFailed() {
  69.         if (eptr) {
  70.             return true;
  71.         } else {
  72.             return false;
  73.         }
  74.     }
  75. protected:
  76.     std::exception_ptr eptr;
  77. };
  78.  
  79. template <class Function, class... Args>
  80. auto TryRun(Function func, Args... args) {
  81.     using ReturnType = decltype(func(args...));
  82.     try {
  83.         func(args...);
  84.     } catch(std::exception& e) {
  85.         Try<ReturnType> rt(e);
  86.         return rt;
  87.     } catch(const char* str) {
  88.         std::runtime_error e(str);
  89.         Try<ReturnType> rt(e);
  90.         return rt;
  91.     } catch(int i) {
  92.         std::runtime_error e(std::strerror(i));
  93.         Try<ReturnType> rt(e);
  94.         return rt;
  95.     } catch(...) {
  96.         std::runtime_error e("Unknown exception");
  97.         Try<ReturnType> rt(e);
  98.         return rt;
  99.     }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement