1 /* Copyright (c) 2005-2016. The SimGrid Team.All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
6 #ifndef SIMGRID_XBT_EXCEPTION_HPP
7 #define SIMGRID_XBT_EXCEPTION_HPP
10 #include <type_traits>
14 #include <xbt/backtrace.h>
15 #include <xbt/backtrace.hpp>
17 #include <xbt/misc.h> // xbt_procname
18 #include <xbt/virtu.h> // xbt_getpid
23 typedef std::vector<xbt_backtrace_location_t> Backtrace;
25 /** A polymorphic mixin class for adding context to an exception */
26 XBT_PUBLIC_CLASS WithContextException {
28 WithContextException() :
29 backtrace_(simgrid::xbt::backtrace()),
30 procname_(xbt_procname()),
33 WithContextException(Backtrace bt) :
34 backtrace_(std::move(bt)),
35 procname_(xbt_procname()),
38 virtual ~WithContextException();
39 Backtrace const& backtrace() const
43 int pid() const { return pid_; }
44 std::string const& processName() const { return procname_; }
47 std::string procname_; /**< Name of the process who thrown this */
48 int pid_; /**< PID of the process who thrown this */
51 /** Internal class used to mixin the two classes */
53 class WithContext : public E, public WithContextException
56 WithContext(E exception)
57 : E(std::move(exception)) {}
58 WithContext(E exception, Backtrace backtrace)
59 : E(std::move(exception)), WithContextException(std::move(backtrace)) {}
60 WithContext(E exception, WithContextException context)
61 : E(std::move(exception)), WithContextException(std::move(context)) {}
62 ~WithContext() override {}
65 /** Throw a given exception a context
67 * @param exception exception to throw
68 * @param backtrace backtrace to attach
72 typename std::enable_if< !std::is_base_of<WithContextException,E>::value >::type
75 // Thanks to the default argument, we are taking the backtrace in the caller:
76 Backtrace backtrace = simgrid::xbt::backtrace())
78 throw WithContext<E>(std::move(exception), std::move(backtrace));