From 3c8ccdd33d4a905741d42dc11039acecef678c3d Mon Sep 17 00:00:00 2001 From: Leonardo de Moura Date: Tue, 18 Feb 2014 10:33:39 -0800 Subject: [PATCH] test(util/exception): experiment with exceptions with nested std::function Signed-off-by: Leonardo de Moura --- src/tests/util/exception.cpp | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/tests/util/exception.cpp b/src/tests/util/exception.cpp index 187e93fef..cfb48024e 100644 --- a/src/tests/util/exception.cpp +++ b/src/tests/util/exception.cpp @@ -5,6 +5,7 @@ Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include +#include #include "util/test.h" #include "util/exception.h" #include "util/sstream.h" @@ -42,10 +43,51 @@ static void tst4() { } } +class ex : public exception { + std::function m_f; + ex(std::function const & f):m_f(f) {} +public: + template ex(F && f):m_f(f) {} + virtual exception * clone() const { return new ex(m_f); } + virtual void rethrow() const { throw *this; } + virtual char const * what() const noexcept { return m_f(); } +}; + +static void throw_ex() { + int x = 10; + std::string msg = "foo"; + throw ex([=]() { + static std::string m; + std::ostringstream buffer; + buffer << "error, x: " << x << " " << msg; + m = buffer.str(); + return m.c_str(); + }); +} + +static void throw_catch_rethrow() { + try { + throw_ex(); + } catch (ex & e) { + std::cout << "CATCH 1: {" << e.what() << "}\n"; + std::unique_ptr new_e(e.clone()); + new_e->rethrow(); + } +} + +static void tst5() { + try { + throw_catch_rethrow(); + } catch (ex & e) { + std::cout << "CATCH 2: {" << e.what() << "}\n"; + } +} + int main() { tst1(); tst2(); tst3(); tst4(); + tst5(); return has_violations() ? 1 : 0; }