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 Py_XINCREF(exception
);
57 PyErr_Restore(exception
, value
, (PyObject
*)NULL
);
61 PyErr_SetNone(PyObject
*exception
)
63 PyErr_SetObject(exception
, (PyObject
*)NULL
);
67 PyErr_SetString(PyObject
*exception
, const char *string
)
69 PyObject
*value
= PyString_FromString(string
);
70 PyErr_SetObject(exception
, value
);
78 PyThreadState
*tstate
= PyThreadState_GET();
80 return tstate
->curexc_type
;
85 PyErr_GivenExceptionMatches(PyObject
*err
, PyObject
*exc
)
87 if (err
== NULL
|| exc
== NULL
) {
88 /* maybe caused by "import exceptions" that failed early on */
91 if (PyTuple_Check(exc
)) {
93 n
= PyTuple_Size(exc
);
94 for (i
= 0; i
< n
; i
++) {
95 /* Test recursively */
96 if (PyErr_GivenExceptionMatches(
97 err
, PyTuple_GET_ITEM(exc
, i
)))
104 /* err might be an instance, so check its class. */
105 if (PyExceptionInstance_Check(err
))
106 err
= PyExceptionInstance_Class(err
);
108 if (PyExceptionClass_Check(err
) && PyExceptionClass_Check(exc
)) {
109 int res
= 0, reclimit
;
110 PyObject
*exception
, *value
, *tb
;
111 PyErr_Fetch(&exception
, &value
, &tb
);
112 /* Temporarily bump the recursion limit, so that in the most
113 common case PyObject_IsSubclass will not raise a recursion
114 error we have to ignore anyway. */
115 reclimit
= Py_GetRecursionLimit();
116 Py_SetRecursionLimit(reclimit
+ 5);
117 res
= PyObject_IsSubclass(err
, exc
);
118 Py_SetRecursionLimit(reclimit
);
119 /* This function must not fail, so print the error here */
121 PyErr_WriteUnraisable(err
);
124 PyErr_Restore(exception
, value
, tb
);
133 PyErr_ExceptionMatches(PyObject
*exc
)
135 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc
);
139 /* Used in many places to normalize a raised exception, including in
140 eval_code2(), do_raise(), and PyErr_Print()
143 PyErr_NormalizeException(PyObject
**exc
, PyObject
**val
, PyObject
**tb
)
145 PyObject
*type
= *exc
;
146 PyObject
*value
= *val
;
147 PyObject
*inclass
= NULL
;
148 PyObject
*initial_tb
= NULL
;
149 PyThreadState
*tstate
= NULL
;
152 /* There was no exception, so nothing to do. */
156 /* If PyErr_SetNone() was used, the value will have been actually
164 if (PyExceptionInstance_Check(value
))
165 inclass
= PyExceptionInstance_Class(value
);
167 /* Normalize the exception so that if the type is a class, the
168 value will be an instance.
170 if (PyExceptionClass_Check(type
)) {
171 /* if the value was not an instance, or is not an instance
172 whose class is (or is derived from) type, then use the
173 value as an argument to instantiation of the type
176 if (!inclass
|| !PyObject_IsSubclass(inclass
, type
)) {
177 PyObject
*args
, *res
;
179 if (value
== Py_None
)
180 args
= PyTuple_New(0);
181 else if (PyTuple_Check(value
)) {
186 args
= PyTuple_Pack(1, value
);
190 res
= PyEval_CallObject(type
, args
);
197 /* if the class of the instance doesn't exactly match the
198 class of the type, believe the instance
200 else if (inclass
!= type
) {
212 /* If the new exception doesn't set a traceback and the old
213 exception had a traceback, use the old traceback for the
214 new exception. It's better than nothing.
217 PyErr_Fetch(exc
, val
, tb
);
218 if (initial_tb
!= NULL
) {
222 Py_DECREF(initial_tb
);
224 /* normalize recursively */
225 tstate
= PyThreadState_GET();
226 if (++tstate
->recursion_depth
> Py_GetRecursionLimit()) {
227 --tstate
->recursion_depth
;
228 /* throw away the old exception... */
231 /* ... and use the recursion error instead */
232 *exc
= PyExc_RuntimeError
;
233 *val
= PyExc_RecursionErrorInst
;
236 /* just keeping the old traceback */
239 PyErr_NormalizeException(exc
, val
, tb
);
240 --tstate
->recursion_depth
;
245 PyErr_Fetch(PyObject
**p_type
, PyObject
**p_value
, PyObject
**p_traceback
)
247 PyThreadState
*tstate
= PyThreadState_GET();
249 *p_type
= tstate
->curexc_type
;
250 *p_value
= tstate
->curexc_value
;
251 *p_traceback
= tstate
->curexc_traceback
;
253 tstate
->curexc_type
= NULL
;
254 tstate
->curexc_value
= NULL
;
255 tstate
->curexc_traceback
= NULL
;
261 PyErr_Restore(NULL
, NULL
, NULL
);
264 /* Convenience functions to set a type error exception and return 0 */
267 PyErr_BadArgument(void)
269 PyErr_SetString(PyExc_TypeError
,
270 "bad argument type for built-in operation");
277 if (PyErr_ExceptionMatches(PyExc_MemoryError
))
278 /* already current */
281 /* raise the pre-allocated instance if it still exists */
282 if (PyExc_MemoryErrorInst
)
283 PyErr_SetObject(PyExc_MemoryError
, PyExc_MemoryErrorInst
);
285 /* this will probably fail since there's no memory and hee,
286 hee, we have to instantiate this class
288 PyErr_SetNone(PyExc_MemoryError
);
294 PyErr_SetFromErrnoWithFilenameObject(PyObject
*exc
, PyObject
*filenameObject
)
304 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
307 if (i
== EINTR
&& PyErr_CheckSignals())
311 rerrstr(errbuf
, sizeof errbuf
);
315 s
= "Error"; /* Sometimes errno didn't get set */
321 /* Note that the Win32 errors do not lineup with the
322 errno error. So if the error is in the MSVC error
323 table, we use it, otherwise we assume it really _is_
326 if (i
> 0 && i
< _sys_nerr
) {
330 int len
= FormatMessage(
331 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
332 FORMAT_MESSAGE_FROM_SYSTEM
|
333 FORMAT_MESSAGE_IGNORE_INSERTS
,
334 NULL
, /* no message source */
336 MAKELANGID(LANG_NEUTRAL
,
338 /* Default language */
340 0, /* size not used */
343 /* Only ever seen this in out-of-mem
345 sprintf(s_small_buf
, "Windows Error 0x%X", i
);
350 /* remove trailing cr/lf and dots */
351 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
356 #endif /* Unix/Windows */
358 if (filenameObject
!= NULL
)
359 v
= Py_BuildValue("(isO)", i
, s
, filenameObject
);
361 v
= Py_BuildValue("(is)", i
, s
);
363 PyErr_SetObject(exc
, v
);
374 PyErr_SetFromErrnoWithFilename(PyObject
*exc
, char *filename
)
376 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
377 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
382 #ifdef Py_WIN_WIDE_FILENAMES
384 PyErr_SetFromErrnoWithUnicodeFilename(PyObject
*exc
, Py_UNICODE
*filename
)
386 PyObject
*name
= filename
?
387 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
389 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
393 #endif /* Py_WIN_WIDE_FILENAMES */
396 PyErr_SetFromErrno(PyObject
*exc
)
398 return PyErr_SetFromErrnoWithFilenameObject(exc
, NULL
);
402 /* Windows specific error code handling */
403 PyObject
*PyErr_SetExcFromWindowsErrWithFilenameObject(
406 PyObject
*filenameObject
)
410 char *s_buf
= NULL
; /* Free via LocalFree */
411 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
413 DWORD err
= (DWORD
)ierr
;
414 if (err
==0) err
= GetLastError();
416 /* Error API error */
417 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
418 FORMAT_MESSAGE_FROM_SYSTEM
|
419 FORMAT_MESSAGE_IGNORE_INSERTS
,
420 NULL
, /* no message source */
422 MAKELANGID(LANG_NEUTRAL
,
423 SUBLANG_DEFAULT
), /* Default language */
425 0, /* size not used */
428 /* Only seen this in out of mem situations */
429 sprintf(s_small_buf
, "Windows Error 0x%X", err
);
434 /* remove trailing cr/lf and dots */
435 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
438 if (filenameObject
!= NULL
)
439 v
= Py_BuildValue("(isO)", err
, s
, filenameObject
);
441 v
= Py_BuildValue("(is)", err
, s
);
443 PyErr_SetObject(exc
, v
);
450 PyObject
*PyErr_SetExcFromWindowsErrWithFilename(
453 const char *filename
)
455 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
456 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
463 #ifdef Py_WIN_WIDE_FILENAMES
464 PyObject
*PyErr_SetExcFromWindowsErrWithUnicodeFilename(
467 const Py_UNICODE
*filename
)
469 PyObject
*name
= filename
?
470 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
472 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
478 #endif /* Py_WIN_WIDE_FILENAMES */
480 PyObject
*PyErr_SetExcFromWindowsErr(PyObject
*exc
, int ierr
)
482 return PyErr_SetExcFromWindowsErrWithFilename(exc
, ierr
, NULL
);
485 PyObject
*PyErr_SetFromWindowsErr(int ierr
)
487 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError
,
490 PyObject
*PyErr_SetFromWindowsErrWithFilename(
492 const char *filename
)
494 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
495 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
502 #ifdef Py_WIN_WIDE_FILENAMES
503 PyObject
*PyErr_SetFromWindowsErrWithUnicodeFilename(
505 const Py_UNICODE
*filename
)
507 PyObject
*name
= filename
?
508 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
510 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
516 #endif /* Py_WIN_WIDE_FILENAMES */
517 #endif /* MS_WINDOWS */
520 _PyErr_BadInternalCall(char *filename
, int lineno
)
522 PyErr_Format(PyExc_SystemError
,
523 "%s:%d: bad argument to internal function",
527 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
528 export the entry point for existing object code: */
529 #undef PyErr_BadInternalCall
531 PyErr_BadInternalCall(void)
533 PyErr_Format(PyExc_SystemError
,
534 "bad argument to internal function");
536 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
541 PyErr_Format(PyObject
*exception
, const char *format
, ...)
546 #ifdef HAVE_STDARG_PROTOTYPES
547 va_start(vargs
, format
);
552 string
= PyString_FromFormatV(format
, vargs
);
553 PyErr_SetObject(exception
, string
);
562 PyErr_NewException(char *name
, PyObject
*base
, PyObject
*dict
)
565 PyObject
*modulename
= NULL
;
566 PyObject
*classname
= NULL
;
567 PyObject
*mydict
= NULL
;
568 PyObject
*bases
= NULL
;
569 PyObject
*result
= NULL
;
570 dot
= strrchr(name
, '.');
572 PyErr_SetString(PyExc_SystemError
,
573 "PyErr_NewException: name must be module.class");
577 base
= PyExc_Exception
;
579 dict
= mydict
= PyDict_New();
583 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
584 modulename
= PyString_FromStringAndSize(name
,
585 (Py_ssize_t
)(dot
-name
));
586 if (modulename
== NULL
)
588 if (PyDict_SetItemString(dict
, "__module__", modulename
) != 0)
591 if (PyTuple_Check(base
)) {
593 /* INCREF as we create a new ref in the else branch */
596 bases
= PyTuple_Pack(1, base
);
600 /* Create a real new-style class. */
601 result
= PyObject_CallFunction((PyObject
*)&PyType_Type
, "sOO",
606 Py_XDECREF(classname
);
607 Py_XDECREF(modulename
);
611 /* Call when an exception has occurred but there is no way for Python
612 to handle it. Examples: exception in __del__ or during GC. */
614 PyErr_WriteUnraisable(PyObject
*obj
)
616 PyObject
*f
, *t
, *v
, *tb
;
617 PyErr_Fetch(&t
, &v
, &tb
);
618 f
= PySys_GetObject("stderr");
620 PyFile_WriteString("Exception ", f
);
622 PyObject
* moduleName
;
624 assert(PyExceptionClass_Check(t
));
625 className
= PyExceptionClass_Name(t
);
626 if (className
!= NULL
) {
627 char *dot
= strrchr(className
, '.');
632 moduleName
= PyObject_GetAttrString(t
, "__module__");
633 if (moduleName
== NULL
)
634 PyFile_WriteString("<unknown>", f
);
636 char* modstr
= PyString_AsString(moduleName
);
638 strcmp(modstr
, "exceptions") != 0)
640 PyFile_WriteString(modstr
, f
);
641 PyFile_WriteString(".", f
);
644 if (className
== NULL
)
645 PyFile_WriteString("<unknown>", f
);
647 PyFile_WriteString(className
, f
);
648 if (v
&& v
!= Py_None
) {
649 PyFile_WriteString(": ", f
);
650 PyFile_WriteObject(v
, f
, 0);
652 Py_XDECREF(moduleName
);
654 PyFile_WriteString(" in ", f
);
655 PyFile_WriteObject(obj
, f
, 0);
656 PyFile_WriteString(" ignored\n", f
);
657 PyErr_Clear(); /* Just in case */
664 extern PyObject
*PyModule_GetWarningsModule(void);
667 /* Set file and line information for the current exception.
668 If the exception is not a SyntaxError, also sets additional attributes
669 to make printing of exceptions believe it is a syntax error. */
672 PyErr_SyntaxLocation(const char *filename
, int lineno
)
674 PyObject
*exc
, *v
, *tb
, *tmp
;
676 /* add attributes for the line number and filename for the error */
677 PyErr_Fetch(&exc
, &v
, &tb
);
678 PyErr_NormalizeException(&exc
, &v
, &tb
);
679 /* XXX check that it is, indeed, a syntax error. It might not
681 tmp
= PyInt_FromLong(lineno
);
685 if (PyObject_SetAttrString(v
, "lineno", tmp
))
689 if (filename
!= NULL
) {
690 tmp
= PyString_FromString(filename
);
694 if (PyObject_SetAttrString(v
, "filename", tmp
))
699 tmp
= PyErr_ProgramText(filename
, lineno
);
701 if (PyObject_SetAttrString(v
, "text", tmp
))
706 if (PyObject_SetAttrString(v
, "offset", Py_None
)) {
709 if (exc
!= PyExc_SyntaxError
) {
710 if (!PyObject_HasAttrString(v
, "msg")) {
711 tmp
= PyObject_Str(v
);
713 if (PyObject_SetAttrString(v
, "msg", tmp
))
720 if (!PyObject_HasAttrString(v
, "print_file_and_line")) {
721 if (PyObject_SetAttrString(v
, "print_file_and_line",
726 PyErr_Restore(exc
, v
, tb
);
729 /* com_fetch_program_text will attempt to load the line of text that
730 the exception refers to. If it fails, it will return NULL but will
731 not set an exception.
733 XXX The functionality of this function is quite similar to the
734 functionality in tb_displayline() in traceback.c.
738 PyErr_ProgramText(const char *filename
, int lineno
)
744 if (filename
== NULL
|| *filename
== '\0' || lineno
<= 0)
746 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
749 for (i
= 0; i
< lineno
; i
++) {
750 char *pLastChar
= &linebuf
[sizeof(linebuf
) - 2];
753 if (Py_UniversalNewlineFgets(linebuf
, sizeof linebuf
, fp
, NULL
) == NULL
)
755 /* fgets read *something*; if it didn't get as
756 far as pLastChar, it must have found a newline
757 or hit the end of the file; if pLastChar is \n,
758 it obviously found a newline; else we haven't
759 yet seen a newline, so must continue */
760 } while (*pLastChar
!= '\0' && *pLastChar
!= '\n');
765 while (*p
== ' ' || *p
== '\t' || *p
== '\014')
767 return PyString_FromString(p
);