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 /* problems here!? not sure PyObject_IsSubclass expects to
110 be called with an exception pending... */
111 return PyObject_IsSubclass(err
, exc
);
119 PyErr_ExceptionMatches(PyObject
*exc
)
121 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc
);
125 /* Used in many places to normalize a raised exception, including in
126 eval_code2(), do_raise(), and PyErr_Print()
129 PyErr_NormalizeException(PyObject
**exc
, PyObject
**val
, PyObject
**tb
)
131 PyObject
*type
= *exc
;
132 PyObject
*value
= *val
;
133 PyObject
*inclass
= NULL
;
134 PyObject
*initial_tb
= NULL
;
135 PyThreadState
*tstate
= NULL
;
138 /* There was no exception, so nothing to do. */
142 /* If PyErr_SetNone() was used, the value will have been actually
150 if (PyExceptionInstance_Check(value
))
151 inclass
= PyExceptionInstance_Class(value
);
153 /* Normalize the exception so that if the type is a class, the
154 value will be an instance.
156 if (PyExceptionClass_Check(type
)) {
157 /* if the value was not an instance, or is not an instance
158 whose class is (or is derived from) type, then use the
159 value as an argument to instantiation of the type
162 if (!inclass
|| !PyObject_IsSubclass(inclass
, type
)) {
163 PyObject
*args
, *res
;
165 if (value
== Py_None
)
166 args
= PyTuple_New(0);
167 else if (PyTuple_Check(value
)) {
172 args
= PyTuple_Pack(1, value
);
176 res
= PyEval_CallObject(type
, args
);
183 /* if the class of the instance doesn't exactly match the
184 class of the type, believe the instance
186 else if (inclass
!= type
) {
198 /* If the new exception doesn't set a traceback and the old
199 exception had a traceback, use the old traceback for the
200 new exception. It's better than nothing.
203 PyErr_Fetch(exc
, val
, tb
);
204 if (initial_tb
!= NULL
) {
208 Py_DECREF(initial_tb
);
210 /* normalize recursively */
211 tstate
= PyThreadState_GET();
212 if (++tstate
->recursion_depth
> Py_GetRecursionLimit()) {
213 --tstate
->recursion_depth
;
214 PyErr_SetObject(PyExc_RuntimeError
, PyExc_RecursionErrorInst
);
217 PyErr_NormalizeException(exc
, val
, tb
);
218 --tstate
->recursion_depth
;
223 PyErr_Fetch(PyObject
**p_type
, PyObject
**p_value
, PyObject
**p_traceback
)
225 PyThreadState
*tstate
= PyThreadState_GET();
227 *p_type
= tstate
->curexc_type
;
228 *p_value
= tstate
->curexc_value
;
229 *p_traceback
= tstate
->curexc_traceback
;
231 tstate
->curexc_type
= NULL
;
232 tstate
->curexc_value
= NULL
;
233 tstate
->curexc_traceback
= NULL
;
239 PyErr_Restore(NULL
, NULL
, NULL
);
242 /* Convenience functions to set a type error exception and return 0 */
245 PyErr_BadArgument(void)
247 PyErr_SetString(PyExc_TypeError
,
248 "bad argument type for built-in operation");
255 if (PyErr_ExceptionMatches(PyExc_MemoryError
))
256 /* already current */
259 /* raise the pre-allocated instance if it still exists */
260 if (PyExc_MemoryErrorInst
)
261 PyErr_SetObject(PyExc_MemoryError
, PyExc_MemoryErrorInst
);
263 /* this will probably fail since there's no memory and hee,
264 hee, we have to instantiate this class
266 PyErr_SetNone(PyExc_MemoryError
);
272 PyErr_SetFromErrnoWithFilenameObject(PyObject
*exc
, PyObject
*filenameObject
)
282 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
285 if (i
== EINTR
&& PyErr_CheckSignals())
289 rerrstr(errbuf
, sizeof errbuf
);
293 s
= "Error"; /* Sometimes errno didn't get set */
299 /* Note that the Win32 errors do not lineup with the
300 errno error. So if the error is in the MSVC error
301 table, we use it, otherwise we assume it really _is_
304 if (i
> 0 && i
< _sys_nerr
) {
308 int len
= FormatMessage(
309 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
310 FORMAT_MESSAGE_FROM_SYSTEM
|
311 FORMAT_MESSAGE_IGNORE_INSERTS
,
312 NULL
, /* no message source */
314 MAKELANGID(LANG_NEUTRAL
,
316 /* Default language */
318 0, /* size not used */
321 /* Only ever seen this in out-of-mem
323 sprintf(s_small_buf
, "Windows Error 0x%X", i
);
328 /* remove trailing cr/lf and dots */
329 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
334 #endif /* Unix/Windows */
336 if (filenameObject
!= NULL
)
337 v
= Py_BuildValue("(isO)", i
, s
, filenameObject
);
339 v
= Py_BuildValue("(is)", i
, s
);
341 PyErr_SetObject(exc
, v
);
352 PyErr_SetFromErrnoWithFilename(PyObject
*exc
, char *filename
)
354 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
355 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
360 #ifdef Py_WIN_WIDE_FILENAMES
362 PyErr_SetFromErrnoWithUnicodeFilename(PyObject
*exc
, Py_UNICODE
*filename
)
364 PyObject
*name
= filename
?
365 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
367 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
371 #endif /* Py_WIN_WIDE_FILENAMES */
374 PyErr_SetFromErrno(PyObject
*exc
)
376 return PyErr_SetFromErrnoWithFilenameObject(exc
, NULL
);
380 /* Windows specific error code handling */
381 PyObject
*PyErr_SetExcFromWindowsErrWithFilenameObject(
384 PyObject
*filenameObject
)
388 char *s_buf
= NULL
; /* Free via LocalFree */
389 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
391 DWORD err
= (DWORD
)ierr
;
392 if (err
==0) err
= GetLastError();
394 /* Error API error */
395 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
396 FORMAT_MESSAGE_FROM_SYSTEM
|
397 FORMAT_MESSAGE_IGNORE_INSERTS
,
398 NULL
, /* no message source */
400 MAKELANGID(LANG_NEUTRAL
,
401 SUBLANG_DEFAULT
), /* Default language */
403 0, /* size not used */
406 /* Only seen this in out of mem situations */
407 sprintf(s_small_buf
, "Windows Error 0x%X", err
);
412 /* remove trailing cr/lf and dots */
413 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
416 if (filenameObject
!= NULL
)
417 v
= Py_BuildValue("(isO)", err
, s
, filenameObject
);
419 v
= Py_BuildValue("(is)", err
, s
);
421 PyErr_SetObject(exc
, v
);
428 PyObject
*PyErr_SetExcFromWindowsErrWithFilename(
431 const char *filename
)
433 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
434 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
441 #ifdef Py_WIN_WIDE_FILENAMES
442 PyObject
*PyErr_SetExcFromWindowsErrWithUnicodeFilename(
445 const Py_UNICODE
*filename
)
447 PyObject
*name
= filename
?
448 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
450 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
456 #endif /* Py_WIN_WIDE_FILENAMES */
458 PyObject
*PyErr_SetExcFromWindowsErr(PyObject
*exc
, int ierr
)
460 return PyErr_SetExcFromWindowsErrWithFilename(exc
, ierr
, NULL
);
463 PyObject
*PyErr_SetFromWindowsErr(int ierr
)
465 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError
,
468 PyObject
*PyErr_SetFromWindowsErrWithFilename(
470 const char *filename
)
472 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
473 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
480 #ifdef Py_WIN_WIDE_FILENAMES
481 PyObject
*PyErr_SetFromWindowsErrWithUnicodeFilename(
483 const Py_UNICODE
*filename
)
485 PyObject
*name
= filename
?
486 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
488 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
494 #endif /* Py_WIN_WIDE_FILENAMES */
495 #endif /* MS_WINDOWS */
498 _PyErr_BadInternalCall(char *filename
, int lineno
)
500 PyErr_Format(PyExc_SystemError
,
501 "%s:%d: bad argument to internal function",
505 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
506 export the entry point for existing object code: */
507 #undef PyErr_BadInternalCall
509 PyErr_BadInternalCall(void)
511 PyErr_Format(PyExc_SystemError
,
512 "bad argument to internal function");
514 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
519 PyErr_Format(PyObject
*exception
, const char *format
, ...)
524 #ifdef HAVE_STDARG_PROTOTYPES
525 va_start(vargs
, format
);
530 string
= PyString_FromFormatV(format
, vargs
);
531 PyErr_SetObject(exception
, string
);
540 PyErr_NewException(char *name
, PyObject
*base
, PyObject
*dict
)
543 PyObject
*modulename
= NULL
;
544 PyObject
*classname
= NULL
;
545 PyObject
*mydict
= NULL
;
546 PyObject
*bases
= NULL
;
547 PyObject
*result
= NULL
;
548 dot
= strrchr(name
, '.');
550 PyErr_SetString(PyExc_SystemError
,
551 "PyErr_NewException: name must be module.class");
555 base
= PyExc_Exception
;
557 dict
= mydict
= PyDict_New();
561 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
562 modulename
= PyString_FromStringAndSize(name
,
563 (Py_ssize_t
)(dot
-name
));
564 if (modulename
== NULL
)
566 if (PyDict_SetItemString(dict
, "__module__", modulename
) != 0)
569 if (PyTuple_Check(base
)) {
571 /* INCREF as we create a new ref in the else branch */
574 bases
= PyTuple_Pack(1, base
);
578 /* Create a real new-style class. */
579 result
= PyObject_CallFunction((PyObject
*)&PyType_Type
, "sOO",
584 Py_XDECREF(classname
);
585 Py_XDECREF(modulename
);
589 /* Call when an exception has occurred but there is no way for Python
590 to handle it. Examples: exception in __del__ or during GC. */
592 PyErr_WriteUnraisable(PyObject
*obj
)
594 PyObject
*f
, *t
, *v
, *tb
;
595 PyErr_Fetch(&t
, &v
, &tb
);
596 f
= PySys_GetObject("stderr");
598 PyFile_WriteString("Exception ", f
);
600 PyObject
* moduleName
;
602 assert(PyExceptionClass_Check(t
));
603 className
= PyExceptionClass_Name(t
);
604 if (className
!= NULL
) {
605 char *dot
= strrchr(className
, '.');
610 moduleName
= PyObject_GetAttrString(t
, "__module__");
611 if (moduleName
== NULL
)
612 PyFile_WriteString("<unknown>", f
);
614 char* modstr
= PyString_AsString(moduleName
);
616 strcmp(modstr
, "exceptions") != 0)
618 PyFile_WriteString(modstr
, f
);
619 PyFile_WriteString(".", f
);
622 if (className
== NULL
)
623 PyFile_WriteString("<unknown>", f
);
625 PyFile_WriteString(className
, f
);
626 if (v
&& v
!= Py_None
) {
627 PyFile_WriteString(": ", f
);
628 PyFile_WriteObject(v
, f
, 0);
630 Py_XDECREF(moduleName
);
632 PyFile_WriteString(" in ", f
);
633 PyFile_WriteObject(obj
, f
, 0);
634 PyFile_WriteString(" ignored\n", f
);
635 PyErr_Clear(); /* Just in case */
642 extern PyObject
*PyModule_GetWarningsModule(void);
645 /* Set file and line information for the current exception.
646 If the exception is not a SyntaxError, also sets additional attributes
647 to make printing of exceptions believe it is a syntax error. */
650 PyErr_SyntaxLocation(const char *filename
, int lineno
)
652 PyObject
*exc
, *v
, *tb
, *tmp
;
654 /* add attributes for the line number and filename for the error */
655 PyErr_Fetch(&exc
, &v
, &tb
);
656 PyErr_NormalizeException(&exc
, &v
, &tb
);
657 /* XXX check that it is, indeed, a syntax error. It might not
659 tmp
= PyInt_FromLong(lineno
);
663 if (PyObject_SetAttrString(v
, "lineno", tmp
))
667 if (filename
!= NULL
) {
668 tmp
= PyString_FromString(filename
);
672 if (PyObject_SetAttrString(v
, "filename", tmp
))
677 tmp
= PyErr_ProgramText(filename
, lineno
);
679 if (PyObject_SetAttrString(v
, "text", tmp
))
684 if (PyObject_SetAttrString(v
, "offset", Py_None
)) {
687 if (exc
!= PyExc_SyntaxError
) {
688 if (!PyObject_HasAttrString(v
, "msg")) {
689 tmp
= PyObject_Str(v
);
691 if (PyObject_SetAttrString(v
, "msg", tmp
))
698 if (!PyObject_HasAttrString(v
, "print_file_and_line")) {
699 if (PyObject_SetAttrString(v
, "print_file_and_line",
704 PyErr_Restore(exc
, v
, tb
);
707 /* com_fetch_program_text will attempt to load the line of text that
708 the exception refers to. If it fails, it will return NULL but will
709 not set an exception.
711 XXX The functionality of this function is quite similar to the
712 functionality in tb_displayline() in traceback.c.
716 PyErr_ProgramText(const char *filename
, int lineno
)
722 if (filename
== NULL
|| *filename
== '\0' || lineno
<= 0)
724 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
727 for (i
= 0; i
< lineno
; i
++) {
728 char *pLastChar
= &linebuf
[sizeof(linebuf
) - 2];
731 if (Py_UniversalNewlineFgets(linebuf
, sizeof linebuf
, fp
, NULL
) == NULL
)
733 /* fgets read *something*; if it didn't get as
734 far as pLastChar, it must have found a newline
735 or hit the end of the file; if pLastChar is \n,
736 it obviously found a newline; else we haven't
737 yet seen a newline, so must continue */
738 } while (*pLastChar
!= '\0' && *pLastChar
!= '\n');
743 while (*p
== ' ' || *p
== '\t' || *p
== '\014')
745 return PyString_FromString(p
);