Mantid
Loading...
Searching...
No Matches
ErrorHandling.cpp
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
7//-------------------------------------------
8// Includes
9//-------------------------------------------
12
13#include <boost/python/extract.hpp>
14#include <boost/python/object.hpp>
15#include <frameobject.h>
16
17#include <sstream>
18#include <stdexcept>
19
20using boost::python::extract;
21
23
24namespace {
25
32void tracebackToStream(std::ostream &msg, PyTracebackObject *traceback, bool root = true) {
33 if (traceback == nullptr)
34 return;
35 msg << "\n ";
36 if (root)
37 msg << "at";
38 else
39 msg << "caused by";
40
41 msg << " line " << traceback->tb_lineno << " in \'"
42 << extract<const char *>(traceback->tb_frame->f_code->co_filename)() << "\'";
43 tracebackToStream(msg, traceback->tb_next, false);
44}
45
56std::string exceptionToString(bool withTrace) {
57 GlobalInterpreterLock gil;
58 PyObject *exception(nullptr), *value(nullptr), *traceback(nullptr);
59 PyErr_Fetch(&exception, &value, &traceback);
60 assert(exception);
61 PyErr_NormalizeException(&exception, &value, &traceback);
62 PyErr_Clear();
63 PyObject *strRepr = PyObject_Str(value);
64 std::stringstream builder;
65 if (value && strRepr) {
66 builder << extract<const char *>(strRepr)();
67 } else {
68 builder << "Unknown exception has occurred.";
69 }
70 if (withTrace) {
71 tracebackToStream(builder, reinterpret_cast<PyTracebackObject *>(traceback));
72 }
73
74 // Ensure we decrement the reference count on the traceback and exception
75 // objects as they hold references to local the stack variables that were
76 // present when the exception was raised. This could include child algorithms
77 // with workspaces stored that would not otherwise be cleaned up until the
78 // program exited.
79 Py_XDECREF(traceback);
80 Py_XDECREF(exception);
81 Py_XDECREF(value);
82 return builder.str();
83}
84} // namespace
85
86// -----------------------------------------------------------------------------
87// PythonException
88// -----------------------------------------------------------------------------
89
95PythonException::PythonException(bool withTrace) : std::runtime_error(exceptionToString(withTrace)) {}
96
97} // namespace Mantid::PythonInterface
double value
The value of the point.
Definition: FitMW.cpp:51
PythonException(bool withTrace=true)
Construct an exception object where the message is populated from the current Python exception state.
STL namespace.