Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <exception>
- #include <stdexcept>
- #include <iostream>
- #include <array>
- #include <exception>
- using namespace std;
- class Exception : public exception {
- public:
- Exception(const char* message): message(message) {
- }
- virtual const char* what() const throw() {
- return message;
- }
- private:
- const char* message;
- };
- template <class T>
- class Try {
- public:
- Try() {
- }
- Try(T value): value(make_unique<T>(value)) {
- }
- Try(const exception& exc): error(exc.what()) {
- }
- const T& Value() const {
- if (value) {
- return *value;
- } else if (error) {
- throw Exception(error);
- } else {
- throw Exception("Object is empty");
- }
- }
- void Throw() {
- if (!error) {
- throw Exception("No exception");
- } else {
- throw Exception(error);
- }
- }
- bool IsFailed() {
- return error;
- }
- private:
- const char* error = nullptr;
- std::unique_ptr<T> value;
- };
- template <class Func, class... Args>
- auto TryRun(Func f, Args&&... args) {
- using T = typename result_of<Func(Args...)>::type;
- try {
- return Try<T>(f(std::forward<Args>(args)...));
- }
- catch (std::exception& exc) {
- return Try<T>(exc);
- }
- catch (const char* msg) {
- return Try<T>(Exception(msg));
- }
- catch (int error) {
- return Try<T>(Exception(strerror(error)));
- }
- catch (...) {
- return Try<T>(Exception("Unknown exception"));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement