Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <exception>
- #include <stdexcept>
- #include <cstring>
- #include <cassert>
- #include <string>
- template <class T>
- class Try {
- public:
- Try() {
- }
- Try(T value) : value(value), empty(false) {
- }
- Try(std::exception& e) {
- try {
- throw e;
- } catch(...) {
- eptr = std::current_exception();
- }
- }
- const T& Value() {
- if (eptr) {
- std::rethrow_exception(eptr);
- } else if (empty) {
- throw std::runtime_error("Object is empty");
- }
- return value;
- }
- virtual void Throw() {
- if (eptr) {
- std::rethrow_exception(eptr);
- } else {
- throw std::runtime_error("No exception");
- }
- }
- bool IsFailed() {
- if (eptr) {
- return true;
- } else {
- return false;
- }
- }
- protected:
- bool empty = true;
- T value{};
- std::exception_ptr eptr;
- };
- template <>
- class Try<void> {
- public:
- Try() {
- }
- Try(std::exception& e) {
- try {
- throw e;
- } catch(...) {
- eptr = std::current_exception();
- }
- }
- virtual void Throw() {
- if (eptr) {
- std::rethrow_exception(eptr);
- } else {
- throw std::runtime_error("No exception");
- }
- }
- bool IsFailed() {
- if (eptr) {
- return true;
- } else {
- return false;
- }
- }
- protected:
- std::exception_ptr eptr;
- };
- template <class Function, class... Args>
- auto TryRun(Function func, Args... args) {
- using ReturnType = decltype(func(args...));
- try {
- func(args...);
- } catch(std::exception& e) {
- Try<ReturnType> rt(e);
- return rt;
- } catch(const char* str) {
- std::runtime_error e(str);
- Try<ReturnType> rt(e);
- return rt;
- } catch(int i) {
- std::runtime_error e(std::strerror(i));
- Try<ReturnType> rt(e);
- return rt;
- } catch(...) {
- std::runtime_error e("Unknown exception");
- Try<ReturnType> rt(e);
- return rt;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement