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
);
118 PyErr_Restore(exception
, value
, tb
);
127 PyErr_ExceptionMatches(PyObject
*exc
)
129 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc
);
133 /* Used in many places to normalize a raised exception, including in
134 eval_code2(), do_raise(), and PyErr_Print()
137 PyErr_NormalizeException(PyObject
**exc
, PyObject
**val
, PyObject
**tb
)
139 PyObject
*type
= *exc
;
140 PyObject
*value
= *val
;
141 PyObject
*inclass
= NULL
;
142 PyObject
*initial_tb
= NULL
;
143 PyThreadState
*tstate
= NULL
;
146 /* There was no exception, so nothing to do. */
150 /* If PyErr_SetNone() was used, the value will have been actually
158 if (PyExceptionInstance_Check(value
))
159 inclass
= PyExceptionInstance_Class(value
);
161 /* Normalize the exception so that if the type is a class, the
162 value will be an instance.
164 if (PyExceptionClass_Check(type
)) {
165 /* if the value was not an instance, or is not an instance
166 whose class is (or is derived from) type, then use the
167 value as an argument to instantiation of the type
170 if (!inclass
|| !PyObject_IsSubclass(inclass
, type
)) {
171 PyObject
*args
, *res
;
173 if (value
== Py_None
)
174 args
= PyTuple_New(0);
175 else if (PyTuple_Check(value
)) {
180 args
= PyTuple_Pack(1, value
);
184 res
= PyEval_CallObject(type
, args
);
191 /* if the class of the instance doesn't exactly match the
192 class of the type, believe the instance
194 else if (inclass
!= type
) {
206 /* If the new exception doesn't set a traceback and the old
207 exception had a traceback, use the old traceback for the
208 new exception. It's better than nothing.
211 PyErr_Fetch(exc
, val
, tb
);
212 if (initial_tb
!= NULL
) {
216 Py_DECREF(initial_tb
);
218 /* normalize recursively */
219 tstate
= PyThreadState_GET();
220 if (++tstate
->recursion_depth
> Py_GetRecursionLimit()) {
221 --tstate
->recursion_depth
;
222 PyErr_SetObject(PyExc_RuntimeError
, PyExc_RecursionErrorInst
);
225 PyErr_NormalizeException(exc
, val
, tb
);
226 --tstate
->recursion_depth
;
231 PyErr_Fetch(PyObject
**p_type
, PyObject
**p_value
, PyObject
**p_traceback
)
233 PyThreadState
*tstate
= PyThreadState_GET();
235 *p_type
= tstate
->curexc_type
;
236 *p_value
= tstate
->curexc_value
;
237 *p_traceback
= tstate
->curexc_traceback
;
239 tstate
->curexc_type
= NULL
;
240 tstate
->curexc_value
= NULL
;
241 tstate
->curexc_traceback
= NULL
;
247 PyErr_Restore(NULL
, NULL
, NULL
);
250 /* Convenience functions to set a type error exception and return 0 */
253 PyErr_BadArgument(void)
255 PyErr_SetString(PyExc_TypeError
,
256 "bad argument type for built-in operation");
263 if (PyErr_ExceptionMatches(PyExc_MemoryError
))
264 /* already current */
267 /* raise the pre-allocated instance if it still exists */
268 if (PyExc_MemoryErrorInst
)
269 PyErr_SetObject(PyExc_MemoryError
, PyExc_MemoryErrorInst
);
271 /* this will probably fail since there's no memory and hee,
272 hee, we have to instantiate this class
274 PyErr_SetNone(PyExc_MemoryError
);
280 PyErr_SetFromErrnoWithFilenameObject(PyObject
*exc
, PyObject
*filenameObject
)
290 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
293 if (i
== EINTR
&& PyErr_CheckSignals())
297 rerrstr(errbuf
, sizeof errbuf
);
301 s
= "Error"; /* Sometimes errno didn't get set */
307 /* Note that the Win32 errors do not lineup with the
308 errno error. So if the error is in the MSVC error
309 table, we use it, otherwise we assume it really _is_
312 if (i
> 0 && i
< _sys_nerr
) {
316 int len
= FormatMessage(
317 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
318 FORMAT_MESSAGE_FROM_SYSTEM
|
319 FORMAT_MESSAGE_IGNORE_INSERTS
,
320 NULL
, /* no message source */
322 MAKELANGID(LANG_NEUTRAL
,
324 /* Default language */
326 0, /* size not used */
329 /* Only ever seen this in out-of-mem
331 sprintf(s_small_buf
, "Windows Error 0x%X", i
);
336 /* remove trailing cr/lf and dots */
337 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
342 #endif /* Unix/Windows */
344 if (filenameObject
!= NULL
)
345 v
= Py_BuildValue("(isO)", i
, s
, filenameObject
);
347 v
= Py_BuildValue("(is)", i
, s
);
349 PyErr_SetObject(exc
, v
);
360 PyErr_SetFromErrnoWithFilename(PyObject
*exc
, char *filename
)
362 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
363 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
368 #ifdef Py_WIN_WIDE_FILENAMES
370 PyErr_SetFromErrnoWithUnicodeFilename(PyObject
*exc
, Py_UNICODE
*filename
)
372 PyObject
*name
= filename
?
373 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
375 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
379 #endif /* Py_WIN_WIDE_FILENAMES */
382 PyErr_SetFromErrno(PyObject
*exc
)
384 return PyErr_SetFromErrnoWithFilenameObject(exc
, NULL
);
388 /* Windows specific error code handling */
389 PyObject
*PyErr_SetExcFromWindowsErrWithFilenameObject(
392 PyObject
*filenameObject
)
396 char *s_buf
= NULL
; /* Free via LocalFree */
397 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
399 DWORD err
= (DWORD
)ierr
;
400 if (err
==0) err
= GetLastError();
402 /* Error API error */
403 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
404 FORMAT_MESSAGE_FROM_SYSTEM
|
405 FORMAT_MESSAGE_IGNORE_INSERTS
,
406 NULL
, /* no message source */
408 MAKELANGID(LANG_NEUTRAL
,
409 SUBLANG_DEFAULT
), /* Default language */
411 0, /* size not used */
414 /* Only seen this in out of mem situations */
415 sprintf(s_small_buf
, "Windows Error 0x%X", err
);
420 /* remove trailing cr/lf and dots */
421 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
424 if (filenameObject
!= NULL
)
425 v
= Py_BuildValue("(isO)", err
, s
, filenameObject
);
427 v
= Py_BuildValue("(is)", err
, s
);
429 PyErr_SetObject(exc
, v
);
436 PyObject
*PyErr_SetExcFromWindowsErrWithFilename(
439 const char *filename
)
441 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
442 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
449 #ifdef Py_WIN_WIDE_FILENAMES
450 PyObject
*PyErr_SetExcFromWindowsErrWithUnicodeFilename(
453 const Py_UNICODE
*filename
)
455 PyObject
*name
= filename
?
456 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
458 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
464 #endif /* Py_WIN_WIDE_FILENAMES */
466 PyObject
*PyErr_SetExcFromWindowsErr(PyObject
*exc
, int ierr
)
468 return PyErr_SetExcFromWindowsErrWithFilename(exc
, ierr
, NULL
);
471 PyObject
*PyErr_SetFromWindowsErr(int ierr
)
473 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError
,
476 PyObject
*PyErr_SetFromWindowsErrWithFilename(
478 const char *filename
)
480 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
481 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
488 #ifdef Py_WIN_WIDE_FILENAMES
489 PyObject
*PyErr_SetFromWindowsErrWithUnicodeFilename(
491 const Py_UNICODE
*filename
)
493 PyObject
*name
= filename
?
494 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
496 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
502 #endif /* Py_WIN_WIDE_FILENAMES */
503 #endif /* MS_WINDOWS */
506 _PyErr_BadInternalCall(char *filename
, int lineno
)
508 PyErr_Format(PyExc_SystemError
,
509 "%s:%d: bad argument to internal function",
513 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
514 export the entry point for existing object code: */
515 #undef PyErr_BadInternalCall
517 PyErr_BadInternalCall(void)
519 PyErr_Format(PyExc_SystemError
,
520 "bad argument to internal function");
522 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
527 PyErr_Format(PyObject
*exception
, const char *format
, ...)
532 #ifdef HAVE_STDARG_PROTOTYPES
533 va_start(vargs
, format
);
538 string
= PyString_FromFormatV(format
, vargs
);
539 PyErr_SetObject(exception
, string
);
548 PyErr_NewException(char *name
, PyObject
*base
, PyObject
*dict
)
551 PyObject
*modulename
= NULL
;
552 PyObject
*classname
= NULL
;
553 PyObject
*mydict
= NULL
;
554 PyObject
*bases
= NULL
;
555 PyObject
*result
= NULL
;
556 dot
= strrchr(name
, '.');
558 PyErr_SetString(PyExc_SystemError
,
559 "PyErr_NewException: name must be module.class");
563 base
= PyExc_Exception
;
565 dict
= mydict
= PyDict_New();
569 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
570 modulename
= PyString_FromStringAndSize(name
,
571 (Py_ssize_t
)(dot
-name
));
572 if (modulename
== NULL
)
574 if (PyDict_SetItemString(dict
, "__module__", modulename
) != 0)
577 if (PyTuple_Check(base
)) {
579 /* INCREF as we create a new ref in the else branch */
582 bases
= PyTuple_Pack(1, base
);
586 /* Create a real new-style class. */
587 result
= PyObject_CallFunction((PyObject
*)&PyType_Type
, "sOO",
592 Py_XDECREF(classname
);
593 Py_XDECREF(modulename
);
597 /* Call when an exception has occurred but there is no way for Python
598 to handle it. Examples: exception in __del__ or during GC. */
600 PyErr_WriteUnraisable(PyObject
*obj
)
602 PyObject
*f
, *t
, *v
, *tb
;
603 PyErr_Fetch(&t
, &v
, &tb
);
604 f
= PySys_GetObject("stderr");
606 PyFile_WriteString("Exception ", f
);
608 PyObject
* moduleName
;
610 assert(PyExceptionClass_Check(t
));
611 className
= PyExceptionClass_Name(t
);
612 if (className
!= NULL
) {
613 char *dot
= strrchr(className
, '.');
618 moduleName
= PyObject_GetAttrString(t
, "__module__");
619 if (moduleName
== NULL
)
620 PyFile_WriteString("<unknown>", f
);
622 char* modstr
= PyString_AsString(moduleName
);
624 strcmp(modstr
, "exceptions") != 0)
626 PyFile_WriteString(modstr
, f
);
627 PyFile_WriteString(".", f
);
630 if (className
== NULL
)
631 PyFile_WriteString("<unknown>", f
);
633 PyFile_WriteString(className
, f
);
634 if (v
&& v
!= Py_None
) {
635 PyFile_WriteString(": ", f
);
636 PyFile_WriteObject(v
, f
, 0);
638 Py_XDECREF(moduleName
);
640 PyFile_WriteString(" in ", f
);
641 PyFile_WriteObject(obj
, f
, 0);
642 PyFile_WriteString(" ignored\n", f
);
643 PyErr_Clear(); /* Just in case */
650 extern PyObject
*PyModule_GetWarningsModule(void);
653 /* Set file and line information for the current exception.
654 If the exception is not a SyntaxError, also sets additional attributes
655 to make printing of exceptions believe it is a syntax error. */
658 PyErr_SyntaxLocation(const char *filename
, int lineno
)
660 PyObject
*exc
, *v
, *tb
, *tmp
;
662 /* add attributes for the line number and filename for the error */
663 PyErr_Fetch(&exc
, &v
, &tb
);
664 PyErr_NormalizeException(&exc
, &v
, &tb
);
665 /* XXX check that it is, indeed, a syntax error. It might not
667 tmp
= PyInt_FromLong(lineno
);
671 if (PyObject_SetAttrString(v
, "lineno", tmp
))
675 if (filename
!= NULL
) {
676 tmp
= PyString_FromString(filename
);
680 if (PyObject_SetAttrString(v
, "filename", tmp
))
685 tmp
= PyErr_ProgramText(filename
, lineno
);
687 if (PyObject_SetAttrString(v
, "text", tmp
))
692 if (PyObject_SetAttrString(v
, "offset", Py_None
)) {
695 if (exc
!= PyExc_SyntaxError
) {
696 if (!PyObject_HasAttrString(v
, "msg")) {
697 tmp
= PyObject_Str(v
);
699 if (PyObject_SetAttrString(v
, "msg", tmp
))
706 if (!PyObject_HasAttrString(v
, "print_file_and_line")) {
707 if (PyObject_SetAttrString(v
, "print_file_and_line",
712 PyErr_Restore(exc
, v
, tb
);
715 /* com_fetch_program_text will attempt to load the line of text that
716 the exception refers to. If it fails, it will return NULL but will
717 not set an exception.
719 XXX The functionality of this function is quite similar to the
720 functionality in tb_displayline() in traceback.c.
724 PyErr_ProgramText(const char *filename
, int lineno
)
730 if (filename
== NULL
|| *filename
== '\0' || lineno
<= 0)
732 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
735 for (i
= 0; i
< lineno
; i
++) {
736 char *pLastChar
= &linebuf
[sizeof(linebuf
) - 2];
739 if (Py_UniversalNewlineFgets(linebuf
, sizeof linebuf
, fp
, NULL
) == NULL
)
741 /* fgets read *something*; if it didn't get as
742 far as pLastChar, it must have found a newline
743 or hit the end of the file; if pLastChar is \n,
744 it obviously found a newline; else we haven't
745 yet seen a newline, so must continue */
746 } while (*pLastChar
!= '\0' && *pLastChar
!= '\n');
751 while (*p
== ' ' || *p
== '\t' || *p
== '\014')
753 return PyString_FromString(p
);