7 #include <torch/csrc/THP_export.h> 8 #include <c10/util/Exception.h> 9 #include <torch/csrc/utils/auto_gil.h> 10 #include <torch/csrc/utils/object_ptr.h> 11 #include <torch/csrc/WindowsTorchApiMacro.h> 13 #define HANDLE_TH_ERRORS \ 15 #define END_HANDLE_TH_ERRORS_RET(retval) \ 17 catch (python_error & e) { \ 20 catch (const c10::IndexError& e) { \ 21 auto msg = torch::processErrorMsg(e.what_without_backtrace()); \ 22 PyErr_SetString(PyExc_IndexError, msg.c_str()); \ 25 catch (const c10::Error& e) { \ 26 auto msg = torch::processErrorMsg(e.what_without_backtrace()); \ 27 PyErr_SetString(PyExc_RuntimeError, msg.c_str()); \ 30 catch (torch::PyTorchError & e) { \ 31 auto msg = torch::processErrorMsg(e.what()); \ 32 PyErr_SetString(e.python_type(), msg.c_str()); \ 35 catch (const std::exception& e) { \ 36 auto msg = torch::processErrorMsg(e.what()); \ 37 PyErr_SetString(PyExc_RuntimeError, msg.c_str()); \ 41 #define END_HANDLE_TH_ERRORS END_HANDLE_TH_ERRORS_RET(nullptr) 43 extern PyObject *THPException_FatalError;
48 python_error() : type(
nullptr), value(
nullptr), traceback(
nullptr) {}
54 Py_XINCREF(traceback);
60 traceback = other.traceback;
62 other.value =
nullptr;
63 other.traceback =
nullptr;
67 if (type || value || traceback) {
71 Py_XDECREF(traceback);
82 Py_XDECREF(traceback);
83 PyErr_Fetch(&type, &value, &traceback);
93 Py_XINCREF(traceback);
94 PyErr_Restore(type, value, traceback);
104 bool THPException_init(PyObject *module);
109 THP_CLASS std::string processErrorMsg(std::string str);
113 virtual PyObject* python_type() = 0;
114 const char* what()
const noexcept
override {
123 PyObject* python_type()
override {
124 return PyExc_IndexError;
130 TORCH_API
TypeError(
const char *format, ...);
131 PyObject* python_type()
override {
132 return PyExc_TypeError;
139 PyObject* python_type()
override {
140 return PyExc_ValueError;
void restore()
Sets the current Python error from this exception.
void persist()
Saves the exception so that it can be re-thrown on a different thread.