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
)) {
110 PyObject
*exception
, *value
, *tb
;
111 PyErr_Fetch(&exception
, &value
, &tb
);
112 res
= PyObject_IsSubclass(err
, exc
);
113 /* This function must not fail, so print the error here */
115 PyErr_WriteUnraisable(err
);
116 /* issubclass did not succeed */
119 PyErr_Restore(exception
, value
, tb
);
128 PyErr_ExceptionMatches(PyObject
*exc
)
130 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc
);
134 /* Used in many places to normalize a raised exception, including in
135 eval_code2(), do_raise(), and PyErr_Print()
138 PyErr_NormalizeException(PyObject
**exc
, PyObject
**val
, PyObject
**tb
)
140 PyObject
*type
= *exc
;
141 PyObject
*value
= *val
;
142 PyObject
*inclass
= NULL
;
143 PyObject
*initial_tb
= NULL
;
144 PyThreadState
*tstate
= NULL
;
147 /* There was no exception, so nothing to do. */
151 /* If PyErr_SetNone() was used, the value will have been actually
159 if (PyExceptionInstance_Check(value
))
160 inclass
= PyExceptionInstance_Class(value
);
162 /* Normalize the exception so that if the type is a class, the
163 value will be an instance.
165 if (PyExceptionClass_Check(type
)) {
166 /* if the value was not an instance, or is not an instance
167 whose class is (or is derived from) type, then use the
168 value as an argument to instantiation of the type
171 if (!inclass
|| !PyObject_IsSubclass(inclass
, type
)) {
172 PyObject
*args
, *res
;
174 if (value
== Py_None
)
175 args
= PyTuple_New(0);
176 else if (PyTuple_Check(value
)) {
181 args
= PyTuple_Pack(1, value
);
185 res
= PyEval_CallObject(type
, args
);
192 /* if the class of the instance doesn't exactly match the
193 class of the type, believe the instance
195 else if (inclass
!= type
) {
207 /* If the new exception doesn't set a traceback and the old
208 exception had a traceback, use the old traceback for the
209 new exception. It's better than nothing.
212 PyErr_Fetch(exc
, val
, tb
);
213 if (initial_tb
!= NULL
) {
217 Py_DECREF(initial_tb
);
219 /* normalize recursively */
220 tstate
= PyThreadState_GET();
221 if (++tstate
->recursion_depth
> Py_GetRecursionLimit()) {
222 --tstate
->recursion_depth
;
223 PyErr_SetObject(PyExc_RuntimeError
, PyExc_RecursionErrorInst
);
226 PyErr_NormalizeException(exc
, val
, tb
);
227 --tstate
->recursion_depth
;
232 PyErr_Fetch(PyObject
**p_type
, PyObject
**p_value
, PyObject
**p_traceback
)
234 PyThreadState
*tstate
= PyThreadState_GET();
236 *p_type
= tstate
->curexc_type
;
237 *p_value
= tstate
->curexc_value
;
238 *p_traceback
= tstate
->curexc_traceback
;
240 tstate
->curexc_type
= NULL
;
241 tstate
->curexc_value
= NULL
;
242 tstate
->curexc_traceback
= NULL
;
248 PyErr_Restore(NULL
, NULL
, NULL
);
251 /* Convenience functions to set a type error exception and return 0 */
254 PyErr_BadArgument(void)
256 PyErr_SetString(PyExc_TypeError
,
257 "bad argument type for built-in operation");
264 if (PyErr_ExceptionMatches(PyExc_MemoryError
))
265 /* already current */
268 /* raise the pre-allocated instance if it still exists */
269 if (PyExc_MemoryErrorInst
)
270 PyErr_SetObject(PyExc_MemoryError
, PyExc_MemoryErrorInst
);
272 /* this will probably fail since there's no memory and hee,
273 hee, we have to instantiate this class
275 PyErr_SetNone(PyExc_MemoryError
);
281 PyErr_SetFromErrnoWithFilenameObject(PyObject
*exc
, PyObject
*filenameObject
)
291 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
294 if (i
== EINTR
&& PyErr_CheckSignals())
298 rerrstr(errbuf
, sizeof errbuf
);
302 s
= "Error"; /* Sometimes errno didn't get set */
308 /* Note that the Win32 errors do not lineup with the
309 errno error. So if the error is in the MSVC error
310 table, we use it, otherwise we assume it really _is_
313 if (i
> 0 && i
< _sys_nerr
) {
317 int len
= FormatMessage(
318 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
319 FORMAT_MESSAGE_FROM_SYSTEM
|
320 FORMAT_MESSAGE_IGNORE_INSERTS
,
321 NULL
, /* no message source */
323 MAKELANGID(LANG_NEUTRAL
,
325 /* Default language */
327 0, /* size not used */
330 /* Only ever seen this in out-of-mem
332 sprintf(s_small_buf
, "Windows Error 0x%X", i
);
337 /* remove trailing cr/lf and dots */
338 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
343 #endif /* Unix/Windows */
345 if (filenameObject
!= NULL
)
346 v
= Py_BuildValue("(isO)", i
, s
, filenameObject
);
348 v
= Py_BuildValue("(is)", i
, s
);
350 PyErr_SetObject(exc
, v
);
361 PyErr_SetFromErrnoWithFilename(PyObject
*exc
, char *filename
)
363 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
364 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
369 #ifdef Py_WIN_WIDE_FILENAMES
371 PyErr_SetFromErrnoWithUnicodeFilename(PyObject
*exc
, Py_UNICODE
*filename
)
373 PyObject
*name
= filename
?
374 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
376 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
380 #endif /* Py_WIN_WIDE_FILENAMES */
383 PyErr_SetFromErrno(PyObject
*exc
)
385 return PyErr_SetFromErrnoWithFilenameObject(exc
, NULL
);
389 /* Windows specific error code handling */
390 PyObject
*PyErr_SetExcFromWindowsErrWithFilenameObject(
393 PyObject
*filenameObject
)
397 char *s_buf
= NULL
; /* Free via LocalFree */
398 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
400 DWORD err
= (DWORD
)ierr
;
401 if (err
==0) err
= GetLastError();
403 /* Error API error */
404 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
405 FORMAT_MESSAGE_FROM_SYSTEM
|
406 FORMAT_MESSAGE_IGNORE_INSERTS
,
407 NULL
, /* no message source */
409 MAKELANGID(LANG_NEUTRAL
,
410 SUBLANG_DEFAULT
), /* Default language */
412 0, /* size not used */
415 /* Only seen this in out of mem situations */
416 sprintf(s_small_buf
, "Windows Error 0x%X", err
);
421 /* remove trailing cr/lf and dots */
422 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
425 if (filenameObject
!= NULL
)
426 v
= Py_BuildValue("(isO)", err
, s
, filenameObject
);
428 v
= Py_BuildValue("(is)", err
, s
);
430 PyErr_SetObject(exc
, v
);
437 PyObject
*PyErr_SetExcFromWindowsErrWithFilename(
440 const char *filename
)
442 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
443 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
450 #ifdef Py_WIN_WIDE_FILENAMES
451 PyObject
*PyErr_SetExcFromWindowsErrWithUnicodeFilename(
454 const Py_UNICODE
*filename
)
456 PyObject
*name
= filename
?
457 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
459 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
465 #endif /* Py_WIN_WIDE_FILENAMES */
467 PyObject
*PyErr_SetExcFromWindowsErr(PyObject
*exc
, int ierr
)
469 return PyErr_SetExcFromWindowsErrWithFilename(exc
, ierr
, NULL
);
472 PyObject
*PyErr_SetFromWindowsErr(int ierr
)
474 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError
,
477 PyObject
*PyErr_SetFromWindowsErrWithFilename(
479 const char *filename
)
481 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
482 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
489 #ifdef Py_WIN_WIDE_FILENAMES
490 PyObject
*PyErr_SetFromWindowsErrWithUnicodeFilename(
492 const Py_UNICODE
*filename
)
494 PyObject
*name
= filename
?
495 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
497 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
503 #endif /* Py_WIN_WIDE_FILENAMES */
504 #endif /* MS_WINDOWS */
507 _PyErr_BadInternalCall(char *filename
, int lineno
)
509 PyErr_Format(PyExc_SystemError
,
510 "%s:%d: bad argument to internal function",
514 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
515 export the entry point for existing object code: */
516 #undef PyErr_BadInternalCall
518 PyErr_BadInternalCall(void)
520 PyErr_Format(PyExc_SystemError
,
521 "bad argument to internal function");
523 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
528 PyErr_Format(PyObject
*exception
, const char *format
, ...)
533 #ifdef HAVE_STDARG_PROTOTYPES
534 va_start(vargs
, format
);
539 string
= PyString_FromFormatV(format
, vargs
);
540 PyErr_SetObject(exception
, string
);
549 PyErr_NewException(char *name
, PyObject
*base
, PyObject
*dict
)
552 PyObject
*modulename
= NULL
;
553 PyObject
*classname
= NULL
;
554 PyObject
*mydict
= NULL
;
555 PyObject
*bases
= NULL
;
556 PyObject
*result
= NULL
;
557 dot
= strrchr(name
, '.');
559 PyErr_SetString(PyExc_SystemError
,
560 "PyErr_NewException: name must be module.class");
564 base
= PyExc_Exception
;
566 dict
= mydict
= PyDict_New();
570 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
571 modulename
= PyString_FromStringAndSize(name
,
572 (Py_ssize_t
)(dot
-name
));
573 if (modulename
== NULL
)
575 if (PyDict_SetItemString(dict
, "__module__", modulename
) != 0)
578 if (PyTuple_Check(base
)) {
580 /* INCREF as we create a new ref in the else branch */
583 bases
= PyTuple_Pack(1, base
);
587 /* Create a real new-style class. */
588 result
= PyObject_CallFunction((PyObject
*)&PyType_Type
, "sOO",
593 Py_XDECREF(classname
);
594 Py_XDECREF(modulename
);
598 /* Call when an exception has occurred but there is no way for Python
599 to handle it. Examples: exception in __del__ or during GC. */
601 PyErr_WriteUnraisable(PyObject
*obj
)
603 PyObject
*f
, *t
, *v
, *tb
;
604 PyErr_Fetch(&t
, &v
, &tb
);
605 f
= PySys_GetObject("stderr");
607 PyFile_WriteString("Exception ", f
);
609 PyObject
* moduleName
;
611 assert(PyExceptionClass_Check(t
));
612 className
= PyExceptionClass_Name(t
);
613 if (className
!= NULL
) {
614 char *dot
= strrchr(className
, '.');
619 moduleName
= PyObject_GetAttrString(t
, "__module__");
620 if (moduleName
== NULL
)
621 PyFile_WriteString("<unknown>", f
);
623 char* modstr
= PyString_AsString(moduleName
);
625 strcmp(modstr
, "exceptions") != 0)
627 PyFile_WriteString(modstr
, f
);
628 PyFile_WriteString(".", f
);
631 if (className
== NULL
)
632 PyFile_WriteString("<unknown>", f
);
634 PyFile_WriteString(className
, f
);
635 if (v
&& v
!= Py_None
) {
636 PyFile_WriteString(": ", f
);
637 PyFile_WriteObject(v
, f
, 0);
639 Py_XDECREF(moduleName
);
641 PyFile_WriteString(" in ", f
);
642 PyFile_WriteObject(obj
, f
, 0);
643 PyFile_WriteString(" ignored\n", f
);
644 PyErr_Clear(); /* Just in case */
651 extern PyObject
*PyModule_GetWarningsModule(void);
654 /* Set file and line information for the current exception.
655 If the exception is not a SyntaxError, also sets additional attributes
656 to make printing of exceptions believe it is a syntax error. */
659 PyErr_SyntaxLocation(const char *filename
, int lineno
)
661 PyObject
*exc
, *v
, *tb
, *tmp
;
663 /* add attributes for the line number and filename for the error */
664 PyErr_Fetch(&exc
, &v
, &tb
);
665 PyErr_NormalizeException(&exc
, &v
, &tb
);
666 /* XXX check that it is, indeed, a syntax error. It might not
668 tmp
= PyInt_FromLong(lineno
);
672 if (PyObject_SetAttrString(v
, "lineno", tmp
))
676 if (filename
!= NULL
) {
677 tmp
= PyString_FromString(filename
);
681 if (PyObject_SetAttrString(v
, "filename", tmp
))
686 tmp
= PyErr_ProgramText(filename
, lineno
);
688 if (PyObject_SetAttrString(v
, "text", tmp
))
693 if (PyObject_SetAttrString(v
, "offset", Py_None
)) {
696 if (exc
!= PyExc_SyntaxError
) {
697 if (!PyObject_HasAttrString(v
, "msg")) {
698 tmp
= PyObject_Str(v
);
700 if (PyObject_SetAttrString(v
, "msg", tmp
))
707 if (!PyObject_HasAttrString(v
, "print_file_and_line")) {
708 if (PyObject_SetAttrString(v
, "print_file_and_line",
713 PyErr_Restore(exc
, v
, tb
);
716 /* com_fetch_program_text will attempt to load the line of text that
717 the exception refers to. If it fails, it will return NULL but will
718 not set an exception.
720 XXX The functionality of this function is quite similar to the
721 functionality in tb_displayline() in traceback.c.
725 PyErr_ProgramText(const char *filename
, int lineno
)
731 if (filename
== NULL
|| *filename
== '\0' || lineno
<= 0)
733 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
736 for (i
= 0; i
< lineno
; i
++) {
737 char *pLastChar
= &linebuf
[sizeof(linebuf
) - 2];
740 if (Py_UniversalNewlineFgets(linebuf
, sizeof linebuf
, fp
, NULL
) == NULL
)
742 /* fgets read *something*; if it didn't get as
743 far as pLastChar, it must have found a newline
744 or hit the end of the file; if pLastChar is \n,
745 it obviously found a newline; else we haven't
746 yet seen a newline, so must continue */
747 } while (*pLastChar
!= '\0' && *pLastChar
!= '\n');
752 while (*p
== ' ' || *p
== '\t' || *p
== '\014')
754 return PyString_FromString(p
);