8 extern char *strerror(int);
25 PyErr_Restore(PyObject
*type
, PyObject
*value
, PyObject
*traceback
)
27 PyThreadState
*tstate
= PyThreadState_GET();
28 PyObject
*oldtype
, *oldvalue
, *oldtraceback
;
30 if (traceback
!= NULL
&& !PyTraceBack_Check(traceback
)) {
31 /* XXX Should never happen -- fatal error instead? */
32 /* Well, it could be None. */
37 /* Save these in locals to safeguard against recursive
38 invocation through Py_XDECREF */
39 oldtype
= tstate
->curexc_type
;
40 oldvalue
= tstate
->curexc_value
;
41 oldtraceback
= tstate
->curexc_traceback
;
43 tstate
->curexc_type
= type
;
44 tstate
->curexc_value
= value
;
45 tstate
->curexc_traceback
= traceback
;
49 Py_XDECREF(oldtraceback
);
53 PyErr_SetObject(PyObject
*exception
, PyObject
*value
)
55 PyThreadState
*tstate
= PyThreadState_GET();
59 if (exception
!= NULL
&&
60 !PyExceptionClass_Check(exception
)) {
61 PyErr_Format(PyExc_SystemError
,
62 "exception %R not a BaseException subclass",
67 exc_value
= tstate
->exc_value
;
68 if (exc_value
!= NULL
&& exc_value
!= Py_None
) {
69 /* Implicit exception chaining */
71 if (value
== NULL
|| !PyExceptionInstance_Check(value
)) {
72 /* We must normalize the value right now */
73 PyObject
*args
, *fixed_value
;
74 if (value
== NULL
|| value
== Py_None
)
75 args
= PyTuple_New(0);
76 else if (PyTuple_Check(value
)) {
81 args
= PyTuple_Pack(1, value
);
83 PyEval_CallObject(exception
, args
) : NULL
;
86 if (fixed_value
== NULL
)
90 /* Avoid reference cycles through the context chain.
91 This is O(chain length) but context chains are
92 usually very short. Sensitive readers may try
93 to inline the call to PyException_GetContext. */
94 if (exc_value
!= value
) {
95 PyObject
*o
= exc_value
, *context
;
96 while ((context
= PyException_GetContext(o
))) {
98 if (context
== value
) {
99 PyException_SetContext(o
, NULL
);
104 PyException_SetContext(value
, exc_value
);
106 Py_DECREF(exc_value
);
109 if (value
!= NULL
&& PyExceptionInstance_Check(value
))
110 tb
= PyException_GetTraceback(value
);
111 Py_XINCREF(exception
);
112 PyErr_Restore(exception
, value
, tb
);
116 PyErr_SetNone(PyObject
*exception
)
118 PyErr_SetObject(exception
, (PyObject
*)NULL
);
122 PyErr_SetString(PyObject
*exception
, const char *string
)
124 PyObject
*value
= PyUnicode_FromString(string
);
125 PyErr_SetObject(exception
, value
);
133 PyThreadState
*tstate
= PyThreadState_GET();
135 return tstate
->curexc_type
;
140 PyErr_GivenExceptionMatches(PyObject
*err
, PyObject
*exc
)
142 if (err
== NULL
|| exc
== NULL
) {
143 /* maybe caused by "import exceptions" that failed early on */
146 if (PyTuple_Check(exc
)) {
148 n
= PyTuple_Size(exc
);
149 for (i
= 0; i
< n
; i
++) {
150 /* Test recursively */
151 if (PyErr_GivenExceptionMatches(
152 err
, PyTuple_GET_ITEM(exc
, i
)))
159 /* err might be an instance, so check its class. */
160 if (PyExceptionInstance_Check(err
))
161 err
= PyExceptionInstance_Class(err
);
163 if (PyExceptionClass_Check(err
) && PyExceptionClass_Check(exc
)) {
165 PyObject
*exception
, *value
, *tb
;
166 PyErr_Fetch(&exception
, &value
, &tb
);
167 /* PyObject_IsSubclass() can recurse and therefore is
168 not safe (see test_bad_getattr in test.pickletester). */
169 res
= PyType_IsSubtype((PyTypeObject
*)err
, (PyTypeObject
*)exc
);
170 /* This function must not fail, so print the error here */
172 PyErr_WriteUnraisable(err
);
175 PyErr_Restore(exception
, value
, tb
);
184 PyErr_ExceptionMatches(PyObject
*exc
)
186 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc
);
190 /* Used in many places to normalize a raised exception, including in
191 eval_code2(), do_raise(), and PyErr_Print()
193 XXX: should PyErr_NormalizeException() also call
194 PyException_SetTraceback() with the resulting value and tb?
197 PyErr_NormalizeException(PyObject
**exc
, PyObject
**val
, PyObject
**tb
)
199 PyObject
*type
= *exc
;
200 PyObject
*value
= *val
;
201 PyObject
*inclass
= NULL
;
202 PyObject
*initial_tb
= NULL
;
203 PyThreadState
*tstate
= NULL
;
206 /* There was no exception, so nothing to do. */
210 /* If PyErr_SetNone() was used, the value will have been actually
218 if (PyExceptionInstance_Check(value
))
219 inclass
= PyExceptionInstance_Class(value
);
221 /* Normalize the exception so that if the type is a class, the
222 value will be an instance.
224 if (PyExceptionClass_Check(type
)) {
225 /* if the value was not an instance, or is not an instance
226 whose class is (or is derived from) type, then use the
227 value as an argument to instantiation of the type
230 if (!inclass
|| !PyObject_IsSubclass(inclass
, type
)) {
231 PyObject
*args
, *res
;
233 if (value
== Py_None
)
234 args
= PyTuple_New(0);
235 else if (PyTuple_Check(value
)) {
240 args
= PyTuple_Pack(1, value
);
244 res
= PyEval_CallObject(type
, args
);
251 /* if the class of the instance doesn't exactly match the
252 class of the type, believe the instance
254 else if (inclass
!= type
) {
266 /* If the new exception doesn't set a traceback and the old
267 exception had a traceback, use the old traceback for the
268 new exception. It's better than nothing.
271 PyErr_Fetch(exc
, val
, tb
);
272 if (initial_tb
!= NULL
) {
276 Py_DECREF(initial_tb
);
278 /* normalize recursively */
279 tstate
= PyThreadState_GET();
280 if (++tstate
->recursion_depth
> Py_GetRecursionLimit()) {
281 --tstate
->recursion_depth
;
282 /* throw away the old exception... */
285 /* ... and use the recursion error instead */
286 *exc
= PyExc_RuntimeError
;
287 *val
= PyExc_RecursionErrorInst
;
290 /* just keeping the old traceback */
293 PyErr_NormalizeException(exc
, val
, tb
);
294 --tstate
->recursion_depth
;
299 PyErr_Fetch(PyObject
**p_type
, PyObject
**p_value
, PyObject
**p_traceback
)
301 PyThreadState
*tstate
= PyThreadState_GET();
303 *p_type
= tstate
->curexc_type
;
304 *p_value
= tstate
->curexc_value
;
305 *p_traceback
= tstate
->curexc_traceback
;
307 tstate
->curexc_type
= NULL
;
308 tstate
->curexc_value
= NULL
;
309 tstate
->curexc_traceback
= NULL
;
315 PyErr_Restore(NULL
, NULL
, NULL
);
318 /* Convenience functions to set a type error exception and return 0 */
321 PyErr_BadArgument(void)
323 PyErr_SetString(PyExc_TypeError
,
324 "bad argument type for built-in operation");
331 if (PyErr_ExceptionMatches(PyExc_MemoryError
))
332 /* already current */
335 /* raise the pre-allocated instance if it still exists */
336 if (PyExc_MemoryErrorInst
)
338 /* Clear the previous traceback, otherwise it will be appended
339 * to the current one.
341 * The following statement is not likely to raise any error;
342 * if it does, we simply discard it.
344 PyException_SetTraceback(PyExc_MemoryErrorInst
, Py_None
);
346 PyErr_SetObject(PyExc_MemoryError
, PyExc_MemoryErrorInst
);
349 /* this will probably fail since there's no memory and hee,
350 hee, we have to instantiate this class
352 PyErr_SetNone(PyExc_MemoryError
);
358 PyErr_SetFromErrnoWithFilenameObject(PyObject
*exc
, PyObject
*filenameObject
)
370 #endif /* Unix/Windows */
374 if (i
== EINTR
&& PyErr_CheckSignals())
379 rerrstr(errbuf
, sizeof errbuf
);
380 message
= PyUnicode_DecodeUTF8(errbuf
, strlen(errbuf
), "ignore");
384 s
= "Error"; /* Sometimes errno didn't get set */
387 message
= PyUnicode_DecodeUTF8(s
, strlen(s
), "ignore");
390 message
= PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
393 /* Note that the Win32 errors do not lineup with the
394 errno error. So if the error is in the MSVC error
395 table, we use it, otherwise we assume it really _is_
398 if (i
> 0 && i
< _sys_nerr
) {
399 message
= PyUnicode_FromString(_sys_errlist
[i
]);
402 int len
= FormatMessageW(
403 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
404 FORMAT_MESSAGE_FROM_SYSTEM
|
405 FORMAT_MESSAGE_IGNORE_INSERTS
,
406 NULL
, /* no message source */
408 MAKELANGID(LANG_NEUTRAL
,
410 /* Default language */
412 0, /* size not used */
415 /* Only ever seen this in out-of-mem
418 message
= PyUnicode_FromFormat("Windows Error 0x%X", i
);
420 /* remove trailing cr/lf and dots */
421 while (len
> 0 && (s_buf
[len
-1] <= L
' ' || s_buf
[len
-1] == L
'.'))
422 s_buf
[--len
] = L
'\0';
423 message
= PyUnicode_FromUnicode(s_buf
, len
);
427 #endif /* Unix/Windows */
438 if (filenameObject
!= NULL
)
439 v
= Py_BuildValue("(iOO)", i
, message
, filenameObject
);
441 v
= Py_BuildValue("(iO)", i
, message
);
445 PyErr_SetObject(exc
, v
);
456 PyErr_SetFromErrnoWithFilename(PyObject
*exc
, const char *filename
)
458 PyObject
*name
= filename
? PyUnicode_FromString(filename
) : NULL
;
459 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
466 PyErr_SetFromErrnoWithUnicodeFilename(PyObject
*exc
, const Py_UNICODE
*filename
)
468 PyObject
*name
= filename
?
469 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
471 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
475 #endif /* MS_WINDOWS */
478 PyErr_SetFromErrno(PyObject
*exc
)
480 return PyErr_SetFromErrnoWithFilenameObject(exc
, NULL
);
484 /* Windows specific error code handling */
485 PyObject
*PyErr_SetExcFromWindowsErrWithFilenameObject(
488 PyObject
*filenameObject
)
491 WCHAR
*s_buf
= NULL
; /* Free via LocalFree */
494 DWORD err
= (DWORD
)ierr
;
495 if (err
==0) err
= GetLastError();
496 len
= FormatMessageW(
497 /* Error API error */
498 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
499 FORMAT_MESSAGE_FROM_SYSTEM
|
500 FORMAT_MESSAGE_IGNORE_INSERTS
,
501 NULL
, /* no message source */
503 MAKELANGID(LANG_NEUTRAL
,
504 SUBLANG_DEFAULT
), /* Default language */
506 0, /* size not used */
509 /* Only seen this in out of mem situations */
510 message
= PyUnicode_FromFormat("Windows Error 0x%X", err
);
513 /* remove trailing cr/lf and dots */
514 while (len
> 0 && (s_buf
[len
-1] <= L
' ' || s_buf
[len
-1] == L
'.'))
515 s_buf
[--len
] = L
'\0';
516 message
= PyUnicode_FromUnicode(s_buf
, len
);
525 if (filenameObject
!= NULL
)
526 v
= Py_BuildValue("(iOO)", err
, message
, filenameObject
);
528 v
= Py_BuildValue("(iO)", err
, message
);
532 PyErr_SetObject(exc
, v
);
539 PyObject
*PyErr_SetExcFromWindowsErrWithFilename(
542 const char *filename
)
544 PyObject
*name
= filename
? PyUnicode_FromString(filename
) : NULL
;
545 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
552 PyObject
*PyErr_SetExcFromWindowsErrWithUnicodeFilename(
555 const Py_UNICODE
*filename
)
557 PyObject
*name
= filename
?
558 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
560 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
567 PyObject
*PyErr_SetExcFromWindowsErr(PyObject
*exc
, int ierr
)
569 return PyErr_SetExcFromWindowsErrWithFilename(exc
, ierr
, NULL
);
572 PyObject
*PyErr_SetFromWindowsErr(int ierr
)
574 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError
,
577 PyObject
*PyErr_SetFromWindowsErrWithFilename(
579 const char *filename
)
581 PyObject
*name
= filename
? PyUnicode_FromString(filename
) : NULL
;
582 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
589 PyObject
*PyErr_SetFromWindowsErrWithUnicodeFilename(
591 const Py_UNICODE
*filename
)
593 PyObject
*name
= filename
?
594 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
596 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
602 #endif /* MS_WINDOWS */
605 _PyErr_BadInternalCall(const char *filename
, int lineno
)
607 PyErr_Format(PyExc_SystemError
,
608 "%s:%d: bad argument to internal function",
612 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
613 export the entry point for existing object code: */
614 #undef PyErr_BadInternalCall
616 PyErr_BadInternalCall(void)
618 PyErr_Format(PyExc_SystemError
,
619 "bad argument to internal function");
621 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
626 PyErr_Format(PyObject
*exception
, const char *format
, ...)
631 #ifdef HAVE_STDARG_PROTOTYPES
632 va_start(vargs
, format
);
637 string
= PyUnicode_FromFormatV(format
, vargs
);
638 PyErr_SetObject(exception
, string
);
647 PyErr_NewException(const char *name
, PyObject
*base
, PyObject
*dict
)
650 PyObject
*modulename
= NULL
;
651 PyObject
*classname
= NULL
;
652 PyObject
*mydict
= NULL
;
653 PyObject
*bases
= NULL
;
654 PyObject
*result
= NULL
;
655 dot
= strrchr(name
, '.');
657 PyErr_SetString(PyExc_SystemError
,
658 "PyErr_NewException: name must be module.class");
662 base
= PyExc_Exception
;
664 dict
= mydict
= PyDict_New();
668 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
669 modulename
= PyUnicode_FromStringAndSize(name
,
670 (Py_ssize_t
)(dot
-name
));
671 if (modulename
== NULL
)
673 if (PyDict_SetItemString(dict
, "__module__", modulename
) != 0)
676 if (PyTuple_Check(base
)) {
678 /* INCREF as we create a new ref in the else branch */
681 bases
= PyTuple_Pack(1, base
);
685 /* Create a real new-style class. */
686 result
= PyObject_CallFunction((PyObject
*)&PyType_Type
, "UOO",
691 Py_XDECREF(classname
);
692 Py_XDECREF(modulename
);
696 /* Call when an exception has occurred but there is no way for Python
697 to handle it. Examples: exception in __del__ or during GC. */
699 PyErr_WriteUnraisable(PyObject
*obj
)
701 PyObject
*f
, *t
, *v
, *tb
;
702 PyErr_Fetch(&t
, &v
, &tb
);
703 f
= PySys_GetObject("stderr");
704 if (f
!= NULL
&& f
!= Py_None
) {
705 PyFile_WriteString("Exception ", f
);
707 PyObject
* moduleName
;
709 assert(PyExceptionClass_Check(t
));
710 className
= PyExceptionClass_Name(t
);
711 if (className
!= NULL
) {
712 char *dot
= strrchr(className
, '.');
717 moduleName
= PyObject_GetAttrString(t
, "__module__");
718 if (moduleName
== NULL
)
719 PyFile_WriteString("<unknown>", f
);
721 char* modstr
= _PyUnicode_AsString(moduleName
);
723 strcmp(modstr
, "builtins") != 0)
725 PyFile_WriteString(modstr
, f
);
726 PyFile_WriteString(".", f
);
729 if (className
== NULL
)
730 PyFile_WriteString("<unknown>", f
);
732 PyFile_WriteString(className
, f
);
733 if (v
&& v
!= Py_None
) {
734 PyFile_WriteString(": ", f
);
735 PyFile_WriteObject(v
, f
, 0);
737 Py_XDECREF(moduleName
);
739 PyFile_WriteString(" in ", f
);
740 PyFile_WriteObject(obj
, f
, 0);
741 PyFile_WriteString(" ignored\n", f
);
742 PyErr_Clear(); /* Just in case */
749 extern PyObject
*PyModule_GetWarningsModule(void);
752 /* Set file and line information for the current exception.
753 If the exception is not a SyntaxError, also sets additional attributes
754 to make printing of exceptions believe it is a syntax error. */
757 PyErr_SyntaxLocation(const char *filename
, int lineno
)
759 PyObject
*exc
, *v
, *tb
, *tmp
;
761 /* add attributes for the line number and filename for the error */
762 PyErr_Fetch(&exc
, &v
, &tb
);
763 PyErr_NormalizeException(&exc
, &v
, &tb
);
764 /* XXX check that it is, indeed, a syntax error. It might not
766 tmp
= PyLong_FromLong(lineno
);
770 if (PyObject_SetAttrString(v
, "lineno", tmp
))
774 if (filename
!= NULL
) {
775 tmp
= PyUnicode_FromString(filename
);
779 if (PyObject_SetAttrString(v
, "filename", tmp
))
784 tmp
= PyErr_ProgramText(filename
, lineno
);
786 if (PyObject_SetAttrString(v
, "text", tmp
))
791 if (PyObject_SetAttrString(v
, "offset", Py_None
)) {
794 if (exc
!= PyExc_SyntaxError
) {
795 if (!PyObject_HasAttrString(v
, "msg")) {
796 tmp
= PyObject_Str(v
);
798 if (PyObject_SetAttrString(v
, "msg", tmp
))
805 if (!PyObject_HasAttrString(v
, "print_file_and_line")) {
806 if (PyObject_SetAttrString(v
, "print_file_and_line",
811 PyErr_Restore(exc
, v
, tb
);
814 /* Attempt to load the line of text that the exception refers to. If it
815 fails, it will return NULL but will not set an exception.
817 XXX The functionality of this function is quite similar to the
818 functionality in tb_displayline() in traceback.c. */
821 PyErr_ProgramText(const char *filename
, int lineno
)
827 if (filename
== NULL
|| *filename
== '\0' || lineno
<= 0)
829 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
832 for (i
= 0; i
< lineno
; i
++) {
833 char *pLastChar
= &linebuf
[sizeof(linebuf
) - 2];
836 if (Py_UniversalNewlineFgets(linebuf
, sizeof linebuf
,
839 /* fgets read *something*; if it didn't get as
840 far as pLastChar, it must have found a newline
841 or hit the end of the file; if pLastChar is \n,
842 it obviously found a newline; else we haven't
843 yet seen a newline, so must continue */
844 } while (*pLastChar
!= '\0' && *pLastChar
!= '\n');
850 while (*p
== ' ' || *p
== '\t' || *p
== '\014')
852 res
= PyUnicode_FromString(p
);