2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2011,2012,2013, by the GROMACS development team, led by
5 * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6 * others, as listed in the AUTHORS file in the top-level source
7 * directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
37 * Declares common exception classes for fatal error handling.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
41 * \ingroup module_utility
43 #ifndef GMX_UTILITY_EXCEPTIONS_H
44 #define GMX_UTILITY_EXCEPTIONS_H
53 #include <boost/exception_ptr.hpp>
54 #include <boost/exception/errinfo_api_function.hpp>
55 #include <boost/exception/errinfo_errno.hpp>
56 #include <boost/exception/exception.hpp>
57 #include <boost/exception/info.hpp>
58 #include <boost/throw_exception.hpp>
65 //! Internal container type for storing a list of nested exceptions.
66 typedef std::vector<boost::exception_ptr> NestedExceptionList;
67 } // namespace internal
74 * Provides information for Gromacs exception constructors.
76 * This class exists to implement common functionality for initializing all
77 * Gromacs exceptions without having extra code in each exception class.
78 * In simple cases, it can be implicitly constructed by passing a simple string
79 * to an exception constructor.
80 * If more complex initialization is necessary, it is possible to explicitly
81 * construct an object of this type and then call other methods to add
82 * information before actually creating the exception object.
85 * With the exception of the reason string, information added with this class
86 * is not currently accessible through any public API, except for calling
87 * printFatalErrorMessage(). This is not implemented as there is no current
88 * need for it, and it is not clear what would be the best alternative for the
89 * access. It should be possible to refactor the internal implementation to
90 * suit the needs of such external access without requiring changes in code
91 * that throws these exceptions.
93 * \ingroup module_utility
95 class ExceptionInitializer
99 * Creates an initialized with the given string as the reason.
101 * \param[in] reason Detailed reason for the exception.
102 * \throw std::bad_alloc if out of memory.
104 * This constructor is not explicit to allow constructing exceptions
105 * with a plain string argument given to the constructor without adding
106 * extra code to each exception class.
108 ExceptionInitializer(const char *reason)
112 //! \copydoc ExceptionInitializer(const char *)
113 ExceptionInitializer(const std::string &reason)
119 * Returns true if addCurrentExceptionAsNested() has been called.
121 * Provided for convenience for cases where exceptions will be added
122 * conditionally, and the caller wants to check whether any excetions
123 * were actually added.
125 bool hasNestedExceptions() const { return !nested_.empty(); }
127 * Adds the currently caught exception as a nested exception.
129 * May be called multiple times; all provided exceptions will be added
130 * in a list of nested exceptions.
132 * Must not be called outside a catch block.
134 void addCurrentExceptionAsNested()
136 nested_.push_back(boost::current_exception());
141 internal::NestedExceptionList nested_;
143 friend class GromacsException;
147 * Base class for all exception objects in Gromacs.
149 * Although boost recommends using virtual inheritance in exception hiearchies,
150 * it is not used here for two reasons:
151 * -# It is only useful when there is diamond inheritance, and that should
152 * never occur in this exception hierarchy because this class is the only
153 * instance of multiple inheritance (Gromacs programming guidelines prohibit
154 * multiple inheritance from concrete classes, but it is unavoidable here
155 * because of the design of boost::exception).
156 * -# Because the constructor takes an argument, virtual inheritance would
157 * complicate any classes that inherit indirectly from this class.
159 * \ingroup module_utility
161 class GromacsException : public std::exception, public boost::exception
165 * Returns the reason string for the exception.
167 * The return value is the string that was passed to the constructor.
169 virtual const char *what() const throw();
171 * Returns the error code corresponding to the exception type.
173 virtual int errorCode() const = 0;
176 * Adds context information to this exception.
178 * \param[in] context Context string to add.
179 * \throws std::bad_alloc if out of memory.
181 * Typical use is to add additional information higher up in the call
182 * stack using this function in a catch block and the rethrow the
186 * The added information is currently not accessible through what(),
187 * nor through any other means except for calling
188 * printFatalErrorMessage(). See ExceptionInitializer for more
191 void prependContext(const std::string &context);
195 * Creates an exception object with the provided initializer/reason.
197 * \param[in] details Initializer for the exception.
198 * \throws std::bad_alloc if out of memory.
200 explicit GromacsException(const ExceptionInitializer &details);
204 * Exception class for file I/O errors.
206 * \ingroup module_utility
208 class FileIOError : public GromacsException
212 * Creates an exception object with the provided initializer/reason.
214 * \param[in] details Initializer for the exception.
215 * \throws std::bad_alloc if out of memory.
217 * It is possible to call this constructor either with an explicit
218 * ExceptionInitializer object (useful for more complex cases), or
219 * a simple string if only a reason string needs to be provided.
221 explicit FileIOError(const ExceptionInitializer &details)
222 : GromacsException(details) {}
224 virtual int errorCode() const;
228 * Exception class for user input errors.
230 * Derived classes should be used to indicate the nature of the error instead
231 * of throwing this class directly.
233 * \ingroup module_utility
235 class UserInputError : public GromacsException
238 //! \copydoc FileIOError::FileIOError()
239 explicit UserInputError(const ExceptionInitializer &details)
240 : GromacsException(details) {}
244 * Exception class for situations where user input cannot be parsed/understood.
246 * \ingroup module_utility
248 class InvalidInputError : public UserInputError
251 //! \copydoc FileIOError::FileIOError()
252 explicit InvalidInputError(const ExceptionInitializer &details)
253 : UserInputError(details) {}
255 virtual int errorCode() const;
259 * Exception class for situations where user input is inconsistent.
261 * \ingroup module_utility
263 class InconsistentInputError : public UserInputError
266 //! \copydoc FileIOError::FileIOError()
267 explicit InconsistentInputError(const ExceptionInitializer &details)
268 : UserInputError(details) {}
270 virtual int errorCode() const;
274 * Exception class for simulation instabilities.
276 * \ingroup module_utility
278 class SimulationInstabilityError : public GromacsException
281 //! \copydoc FileIOError::FileIOError()
282 explicit SimulationInstabilityError(const ExceptionInitializer &details)
283 : GromacsException(details) {}
285 virtual int errorCode() const;
289 * Exception class for internal errors.
291 * \ingroup module_utility
293 class InternalError : public GromacsException
296 //! \copydoc FileIOError::FileIOError()
297 explicit InternalError(const ExceptionInitializer &details)
298 : GromacsException(details) {}
300 virtual int errorCode() const;
304 * Exception class for incorrect use of an API.
306 * \ingroup module_utility
308 class APIError : public GromacsException
311 //! \copydoc FileIOError::FileIOError()
312 explicit APIError(const ExceptionInitializer &details)
313 : GromacsException(details) {}
315 virtual int errorCode() const;
319 * Exception class for use of an unimplemented feature.
321 * \ingroup module_utility
323 class NotImplementedError : public APIError
326 //! \copydoc FileIOError::FileIOError()
327 explicit NotImplementedError(const ExceptionInitializer &details)
328 : APIError(details) {}
330 virtual int errorCode() const;
335 * Macro for throwing an exception.
337 * \param[in] e Exception object to throw.
339 * Using this macro instead of \c throw directly makes it possible to uniformly
340 * attach information into the exception objects.
341 * \p e should evaluate to an instance of an object derived from
348 GMX_THROW(InconsistentUserInput("Negative values not allowed for value"));
352 #define GMX_THROW(e) \
353 BOOST_THROW_EXCEPTION((e))
356 * Macro for throwing an exception based on errno.
358 * \param[in] e Exception object to throw.
359 * \param[in] syscall Name of the syscall that returned the error.
360 * \param[in] err errno value returned by the syscall.
362 * This macro provides a convenience interface for throwing an exception to
363 * report an error based on a errno value. In addition to adding the necessary
364 * information to the exception object, the macro also ensures that \p errno is
365 * evaluated before, e.g., the constructor of \p e may call other functions
366 * that could overwrite the errno value.
367 * \p e should evaluate to an instance of an object derived from
370 * Typical usage (note that gmx::File wraps this particular case):
372 FILE *fp = fopen("filename.txt", "r");
375 GMX_THROW(FileIOError("Could not open file"), "fopen", errno);
379 #define GMX_THROW_WITH_ERRNO(e, syscall, err) \
381 int stored_errno_ = (err); \
382 GMX_THROW((e) << boost::errinfo_errno(stored_errno_) \
383 << boost::errinfo_api_function(syscall)); \
387 * Formats a standard fatal error message for reporting an exception.
389 * \param[in] fp File to format the message to.
390 * \param[in] ex Exception to format.
392 * Does not throw. If memory allocation fails or some other error occurs
393 * while formatting the error, tries to print a reasonable alternative message.
395 * Normal usage in Gromacs command-line programs is like this:
397 int main(int argc, char *argv[])
399 gmx::ProgramInfo::init(argc, argv);
402 // The actual code for the program
405 catch (const std::exception &ex)
407 gmx::printFatalErrorMessage(stderr, ex);
413 void printFatalErrorMessage(FILE *fp, const std::exception &ex);
415 * Formats an error message for reporting an exception.
417 * \param[in] ex Exception to format.
418 * \returns Formatted string containing details of \p ex.
419 * \throws std::bad_alloc if out of memory.
421 * Currently, the output format is useful mainly for tests and debugging
422 * purposes; additional flags for controlling the format can be added if other
423 * uses for the function arise.
425 std::string formatException(const std::exception &ex);
428 * Converts an exception into a return code.
430 int translateException(const std::exception &ex);
435 /*! \libinternal \brief
436 * Macro for catching exceptions at C++ -> C boundary.
438 * This macro is intended for uniform handling of exceptions when C++ code is
439 * called from C code within Gromacs. Since most existing code is written
440 * using the assumption that fatal errors terminate the program, this macro
441 * implements this behavior for exceptions. It should only be used in cases
442 * where the error cannot be propagated upwards using return values or such.
444 * Having this as a macro instead of having the same code in each place makes
445 * it easy to 1) find all such locations in the code, and 2) change the exact
446 * behavior if needed.
454 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
459 #define GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR \
460 catch (const std::exception &ex) { \
461 ::gmx::printFatalErrorMessage(stderr, ex); \