Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add a section on errors and exceptions to the API documentation
[simgrid.git] / include / simgrid / Exception.hpp
1 /* Copyright (c) 2018-2023. The SimGrid Team. All rights reserved.          */
2
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. */
5
6 /* This file defines all possible exception that could occur in a SimGrid library. */
7
8 #ifndef SIMGRID_EXCEPTIONS_HPP
9 #define SIMGRID_EXCEPTIONS_HPP
10
11 #include <xbt/backtrace.hpp>
12 #include <xbt/ex.h>
13 #include <xbt/string.hpp>
14
15 #include <atomic>
16 #include <functional>
17 #include <stdexcept>
18 #include <string>
19
20 namespace simgrid {
21 namespace xbt {
22
23 /** Contextual information about an execution location (file:line:func and backtrace, procname, pid)
24  *
25  *  Constitute the contextual information of where an exception was thrown
26  *
27  *  These tuples (__FILE__, __LINE__, __func__, backtrace, procname, pid)
28  *  are best created with the macro XBT_THROW_POINT.
29  */
30 class ThrowPoint {
31 public:
32   ThrowPoint() = default;
33   explicit ThrowPoint(const char* file, int line, const char* function, Backtrace&& bt, std::string&& actor_name,
34                       int pid)
35       : file_(file)
36       , line_(line)
37       , function_(function)
38       , backtrace_(std::move(bt))
39       , procname_(std::move(actor_name))
40       , pid_(pid)
41   {
42   }
43
44   const char* file_     = nullptr;
45   int line_             = 0;
46   const char* function_ = nullptr;
47   Backtrace backtrace_;
48   std::string procname_ = ""; /**< Name of the process who thrown this */
49   int pid_              = 0;  /**< PID of the process who thrown this */
50 };
51
52 /** Create a ThrowPoint with (__FILE__, __LINE__, __func__) */
53 #define XBT_THROW_POINT                                                                                                \
54   ::simgrid::xbt::ThrowPoint(__FILE__, __LINE__, __func__, simgrid::xbt::Backtrace(), xbt_procname(), xbt_getpid())
55
56 class XBT_PUBLIC ImpossibleError : public std::logic_error {
57 public:
58   using std::logic_error::logic_error;
59   ~ImpossibleError() override;
60 };
61
62 class XBT_PUBLIC InitializationError : public std::logic_error {
63 public:
64   using std::logic_error::logic_error;
65   ~InitializationError() override;
66 };
67
68 class XBT_PUBLIC UnimplementedError : public std::logic_error {
69 public:
70   using std::logic_error::logic_error;
71   ~UnimplementedError() override;
72 };
73
74 } // namespace xbt
75
76 /** Ancestor class of all SimGrid exception */
77 class Exception : public std::runtime_error {
78 public:
79   Exception(simgrid::xbt::ThrowPoint&& throwpoint, const std::string& message)
80       : std::runtime_error(message), throwpoint_(std::move(throwpoint))
81   {
82   }
83   Exception(const Exception&)     = default;
84   Exception(Exception&&) noexcept = default;
85   ~Exception() override; // DO NOT define it here -- see Exception.cpp for a rationale
86
87   /** Return the information about where the exception was thrown */
88   xbt::ThrowPoint const& throw_point() const { return throwpoint_; }
89
90   /** Allow to carry a value (used by testany/waitany) */
91   ssize_t get_value() const { return value_; }
92   void set_value(ssize_t value) { value_ = value; }
93
94   std::string resolve_backtrace() const { return throwpoint_.backtrace_.resolve(); }
95
96   XBT_ATTRIB_NORETURN virtual void rethrow_nested(simgrid::xbt::ThrowPoint&& throwpoint,
97                                                   const std::string& message) const
98   {
99     std::throw_with_nested(Exception(std::move(throwpoint), message));
100   }
101
102 private:
103   xbt::ThrowPoint throwpoint_;
104   ssize_t value_ = 0;
105 };
106
107 #define DECLARE_SIMGRID_EXCEPTION(AnyException, ...)                                                                   \
108   class AnyException : public Exception {                                                                              \
109   public:                                                                                                              \
110     using Exception::Exception;                                                                                        \
111     __VA_ARGS__                                                                                                        \
112     ~AnyException() override;                                                                                          \
113     XBT_ATTRIB_NORETURN void rethrow_nested(simgrid::xbt::ThrowPoint&& throwpoint,                                     \
114                                             const std::string& message) const override                                 \
115     {                                                                                                                  \
116       std::throw_with_nested(AnyException(std::move(throwpoint), message));                                            \
117     }                                                                                                                  \
118   }
119
120 /** Exception raised when a timeout elapsed */
121 DECLARE_SIMGRID_EXCEPTION(TimeoutException);
122
123 /** Exception raised when a host fails */
124 DECLARE_SIMGRID_EXCEPTION(HostFailureException);
125
126 /** Exception raised when a communication fails because of the network or because of the remote host */
127 DECLARE_SIMGRID_EXCEPTION(NetworkFailureException);
128
129 /** Exception raised when a storage fails */
130 DECLARE_SIMGRID_EXCEPTION(StorageFailureException);
131
132 /** Exception raised when a VM fails */
133 DECLARE_SIMGRID_EXCEPTION(VmFailureException);
134
135 /** Exception raised when something got canceled before completion */
136 DECLARE_SIMGRID_EXCEPTION(CancelException);
137
138 /** Exception raised when something is going wrong during the simulation tracing */
139 DECLARE_SIMGRID_EXCEPTION(TracingError);
140
141 /** Exception raised when something is going wrong during the parsing of XML files */
142 #define PARSE_ERROR_CONSTRUCTOR                                                                                        \
143   ParseError(const std::string& file, int line, const std::string& msg)                                                \
144       : Exception(XBT_THROW_POINT, xbt::string_printf("Parse error at %s:%d: %s", file.c_str(), line, msg.c_str()))    \
145   {                                                                                                                    \
146   }
147
148 DECLARE_SIMGRID_EXCEPTION(ParseError, PARSE_ERROR_CONSTRUCTOR);
149 #undef PARSE_ERROR_CONSTRUCTOR
150
151 /** Exception raised by xbt_enforce, when an assertion is not satisfied */
152 DECLARE_SIMGRID_EXCEPTION(AssertionError);
153
154 #undef DECLARE_SIMGRID_EXCEPTION
155
156 class XBT_PUBLIC ForcefulKillException {
157   /** @brief Exception launched to kill an actor; DO NOT BLOCK IT!
158    *
159    * This exception is thrown whenever the actor's host is turned off. The actor stack is properly unwinded to release
160    * all objects allocated on the stack (RAII powa).
161    *
162    * You may want to catch this exception to perform some extra cleanups in your simulation, but YOUR ACTORS MUST NEVER
163    * SURVIVE a ForcefulKillException, or your simulation will segfault.
164    *
165    * @verbatim
166    * void* payload = malloc(512);
167    *
168    * try {
169    *   simgrid::s4u::this_actor::execute(100000);
170    * } catch (simgrid::kernel::context::ForcefulKillException& e) { // oops, my host just turned off
171    *   free(malloc);
172    *   throw; // I shall never survive on a host that was switched off
173    * }
174    * @endverbatim
175    */
176   /* Nope, Sonar, this should not inherit of std::exception nor of simgrid::Exception.
177    * Otherwise, users may accidentally catch it with a try {} catch (std::exception)
178    */
179 public:
180   ForcefulKillException() = default;
181   explicit ForcefulKillException(const std::string& msg) : msg_("Actor killed (" + msg + ").") {}
182   ~ForcefulKillException();
183   const char* what() const noexcept { return msg_.c_str(); }
184
185   XBT_ATTRIB_NORETURN static void do_throw();
186   static bool try_n_catch(const std::function<void()>& try_block);
187
188 private:
189   std::string msg_ = "Actor killed.";
190 };
191
192 } // namespace simgrid
193 #endif