Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <exception>
  4. #include <stdexcept>
  5.  
  6. #include <iostream>
  7. #include <array>
  8. #include <exception>
  9.  
  10. using namespace std;
  11.  
  12.  
  13. class Exception : public exception {
  14. public:
  15.     Exception(const char* message): message(message) {
  16.     }
  17.  
  18.     virtual const char* what() const throw() {
  19.         return message;
  20.     }
  21. private:
  22.     const char* message;
  23. };
  24.  
  25.  
  26. template <class T>
  27. class Try {
  28. public:
  29.     Try() {
  30.     }
  31.  
  32.     Try(T value): value(make_unique<T>(value)) {
  33.     }
  34.  
  35.     Try(const exception& exc): error(exc.what()) {
  36.     }
  37.  
  38.     const T& Value() const {
  39.         if (value) {
  40.             return *value;
  41.         } else if (error) {
  42.             throw Exception(error);
  43.         } else {
  44.             throw Exception("Object is empty");
  45.         }
  46.     }
  47.  
  48.     void Throw() {
  49.         if (!error) {
  50.             throw Exception("No exception");
  51.         } else {
  52.             throw Exception(error);
  53.         }
  54.     }
  55.  
  56.     bool IsFailed() {
  57.         return error;
  58.     }
  59. private:
  60.     const char* error = nullptr;
  61.     std::unique_ptr<T> value;
  62. };
  63.  
  64.  
  65. template <class Func, class... Args>
  66. auto TryRun(Func f, Args&&... args) {
  67.     using T = typename result_of<Func(Args...)>::type;
  68.     try {
  69.         return Try<T>(f(std::forward<Args>(args)...));
  70.     }
  71.     catch (std::exception& exc) {
  72.         return Try<T>(exc);
  73.     }
  74.     catch (const char* msg) {
  75.         return Try<T>(Exception(msg));
  76.     }
  77.     catch (int error) {
  78.         return Try<T>(Exception(strerror(error)));
  79.     }
  80.     catch (...) {
  81.         return Try<T>(Exception("Unknown exception"));
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement