8 extern char *strerror(int);
20 PyErr_Restore(PyObject
*type
, PyObject
*value
, PyObject
*traceback
)
22 PyThreadState
*tstate
= PyThreadState_GET();
23 PyObject
*oldtype
, *oldvalue
, *oldtraceback
;
25 if (traceback
!= NULL
&& !PyTraceBack_Check(traceback
)) {
26 /* XXX Should never happen -- fatal error instead? */
27 /* Well, it could be None. */
32 /* Save these in locals to safeguard against recursive
33 invocation through Py_XDECREF */
34 oldtype
= tstate
->curexc_type
;
35 oldvalue
= tstate
->curexc_value
;
36 oldtraceback
= tstate
->curexc_traceback
;
38 tstate
->curexc_type
= type
;
39 tstate
->curexc_value
= value
;
40 tstate
->curexc_traceback
= traceback
;
44 Py_XDECREF(oldtraceback
);
48 PyErr_SetObject(PyObject
*exception
, PyObject
*value
)
50 Py_XINCREF(exception
);
52 PyErr_Restore(exception
, value
, (PyObject
*)NULL
);
56 PyErr_SetNone(PyObject
*exception
)
58 PyErr_SetObject(exception
, (PyObject
*)NULL
);
62 PyErr_SetString(PyObject
*exception
, const char *string
)
64 PyObject
*value
= PyString_FromString(string
);
65 PyErr_SetObject(exception
, value
);
73 PyThreadState
*tstate
= PyThreadState_GET();
75 return tstate
->curexc_type
;
80 PyErr_GivenExceptionMatches(PyObject
*err
, PyObject
*exc
)
82 if (err
== NULL
|| exc
== NULL
) {
83 /* maybe caused by "import exceptions" that failed early on */
86 if (PyTuple_Check(exc
)) {
88 n
= PyTuple_Size(exc
);
89 for (i
= 0; i
< n
; i
++) {
90 /* Test recursively */
91 if (PyErr_GivenExceptionMatches(
92 err
, PyTuple_GET_ITEM(exc
, i
)))
99 /* err might be an instance, so check its class. */
100 if (PyExceptionInstance_Check(err
))
101 err
= PyExceptionInstance_Class(err
);
103 if (PyExceptionClass_Check(err
) && PyExceptionClass_Check(exc
)) {
104 /* problems here!? not sure PyObject_IsSubclass expects to
105 be called with an exception pending... */
106 return PyObject_IsSubclass(err
, exc
);
114 PyErr_ExceptionMatches(PyObject
*exc
)
116 return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc
);
120 /* Used in many places to normalize a raised exception, including in
121 eval_code2(), do_raise(), and PyErr_Print()
124 PyErr_NormalizeException(PyObject
**exc
, PyObject
**val
, PyObject
**tb
)
126 PyObject
*type
= *exc
;
127 PyObject
*value
= *val
;
128 PyObject
*inclass
= NULL
;
129 PyObject
*initial_tb
= NULL
;
132 /* There was no exception, so nothing to do. */
136 /* If PyErr_SetNone() was used, the value will have been actually
144 if (PyExceptionInstance_Check(value
))
145 inclass
= PyExceptionInstance_Class(value
);
147 /* Normalize the exception so that if the type is a class, the
148 value will be an instance.
150 if (PyExceptionClass_Check(type
)) {
151 /* if the value was not an instance, or is not an instance
152 whose class is (or is derived from) type, then use the
153 value as an argument to instantiation of the type
156 if (!inclass
|| !PyObject_IsSubclass(inclass
, type
)) {
157 PyObject
*args
, *res
;
159 if (value
== Py_None
)
160 args
= PyTuple_New(0);
161 else if (PyTuple_Check(value
)) {
166 args
= PyTuple_Pack(1, value
);
170 res
= PyEval_CallObject(type
, args
);
177 /* if the class of the instance doesn't exactly match the
178 class of the type, believe the instance
180 else if (inclass
!= type
) {
192 /* If the new exception doesn't set a traceback and the old
193 exception had a traceback, use the old traceback for the
194 new exception. It's better than nothing.
197 PyErr_Fetch(exc
, val
, tb
);
198 if (initial_tb
!= NULL
) {
202 Py_DECREF(initial_tb
);
204 /* normalize recursively */
205 PyErr_NormalizeException(exc
, val
, tb
);
210 PyErr_Fetch(PyObject
**p_type
, PyObject
**p_value
, PyObject
**p_traceback
)
212 PyThreadState
*tstate
= PyThreadState_GET();
214 *p_type
= tstate
->curexc_type
;
215 *p_value
= tstate
->curexc_value
;
216 *p_traceback
= tstate
->curexc_traceback
;
218 tstate
->curexc_type
= NULL
;
219 tstate
->curexc_value
= NULL
;
220 tstate
->curexc_traceback
= NULL
;
226 PyErr_Restore(NULL
, NULL
, NULL
);
229 /* Convenience functions to set a type error exception and return 0 */
232 PyErr_BadArgument(void)
234 PyErr_SetString(PyExc_TypeError
,
235 "bad argument type for built-in operation");
242 if (PyErr_ExceptionMatches(PyExc_MemoryError
))
243 /* already current */
246 /* raise the pre-allocated instance if it still exists */
247 if (PyExc_MemoryErrorInst
)
248 PyErr_SetObject(PyExc_MemoryError
, PyExc_MemoryErrorInst
);
250 /* this will probably fail since there's no memory and hee,
251 hee, we have to instantiate this class
253 PyErr_SetNone(PyExc_MemoryError
);
259 PyErr_SetFromErrnoWithFilenameObject(PyObject
*exc
, PyObject
*filenameObject
)
269 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
272 if (i
== EINTR
&& PyErr_CheckSignals())
276 rerrstr(errbuf
, sizeof errbuf
);
280 s
= "Error"; /* Sometimes errno didn't get set */
286 /* Note that the Win32 errors do not lineup with the
287 errno error. So if the error is in the MSVC error
288 table, we use it, otherwise we assume it really _is_
291 if (i
> 0 && i
< _sys_nerr
) {
295 int len
= FormatMessage(
296 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
297 FORMAT_MESSAGE_FROM_SYSTEM
|
298 FORMAT_MESSAGE_IGNORE_INSERTS
,
299 NULL
, /* no message source */
301 MAKELANGID(LANG_NEUTRAL
,
303 /* Default language */
305 0, /* size not used */
308 /* Only ever seen this in out-of-mem
310 sprintf(s_small_buf
, "Windows Error 0x%X", i
);
315 /* remove trailing cr/lf and dots */
316 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
321 #endif /* Unix/Windows */
323 if (filenameObject
!= NULL
)
324 v
= Py_BuildValue("(isO)", i
, s
, filenameObject
);
326 v
= Py_BuildValue("(is)", i
, s
);
328 PyErr_SetObject(exc
, v
);
339 PyErr_SetFromErrnoWithFilename(PyObject
*exc
, char *filename
)
341 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
342 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
347 #ifdef Py_WIN_WIDE_FILENAMES
349 PyErr_SetFromErrnoWithUnicodeFilename(PyObject
*exc
, Py_UNICODE
*filename
)
351 PyObject
*name
= filename
?
352 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
354 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
358 #endif /* Py_WIN_WIDE_FILENAMES */
361 PyErr_SetFromErrno(PyObject
*exc
)
363 return PyErr_SetFromErrnoWithFilenameObject(exc
, NULL
);
367 /* Windows specific error code handling */
368 PyObject
*PyErr_SetExcFromWindowsErrWithFilenameObject(
371 PyObject
*filenameObject
)
375 char *s_buf
= NULL
; /* Free via LocalFree */
376 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
378 DWORD err
= (DWORD
)ierr
;
379 if (err
==0) err
= GetLastError();
381 /* Error API error */
382 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
383 FORMAT_MESSAGE_FROM_SYSTEM
|
384 FORMAT_MESSAGE_IGNORE_INSERTS
,
385 NULL
, /* no message source */
387 MAKELANGID(LANG_NEUTRAL
,
388 SUBLANG_DEFAULT
), /* Default language */
390 0, /* size not used */
393 /* Only seen this in out of mem situations */
394 sprintf(s_small_buf
, "Windows Error 0x%X", err
);
399 /* remove trailing cr/lf and dots */
400 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
403 if (filenameObject
!= NULL
)
404 v
= Py_BuildValue("(isO)", err
, s
, filenameObject
);
406 v
= Py_BuildValue("(is)", err
, s
);
408 PyErr_SetObject(exc
, v
);
415 PyObject
*PyErr_SetExcFromWindowsErrWithFilename(
418 const char *filename
)
420 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
421 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
428 #ifdef Py_WIN_WIDE_FILENAMES
429 PyObject
*PyErr_SetExcFromWindowsErrWithUnicodeFilename(
432 const Py_UNICODE
*filename
)
434 PyObject
*name
= filename
?
435 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
437 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
443 #endif /* Py_WIN_WIDE_FILENAMES */
445 PyObject
*PyErr_SetExcFromWindowsErr(PyObject
*exc
, int ierr
)
447 return PyErr_SetExcFromWindowsErrWithFilename(exc
, ierr
, NULL
);
450 PyObject
*PyErr_SetFromWindowsErr(int ierr
)
452 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError
,
455 PyObject
*PyErr_SetFromWindowsErrWithFilename(
457 const char *filename
)
459 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
460 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
467 #ifdef Py_WIN_WIDE_FILENAMES
468 PyObject
*PyErr_SetFromWindowsErrWithUnicodeFilename(
470 const Py_UNICODE
*filename
)
472 PyObject
*name
= filename
?
473 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
475 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
481 #endif /* Py_WIN_WIDE_FILENAMES */
482 #endif /* MS_WINDOWS */
485 _PyErr_BadInternalCall(char *filename
, int lineno
)
487 PyErr_Format(PyExc_SystemError
,
488 "%s:%d: bad argument to internal function",
492 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
493 export the entry point for existing object code: */
494 #undef PyErr_BadInternalCall
496 PyErr_BadInternalCall(void)
498 PyErr_Format(PyExc_SystemError
,
499 "bad argument to internal function");
501 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
506 PyErr_Format(PyObject
*exception
, const char *format
, ...)
511 #ifdef HAVE_STDARG_PROTOTYPES
512 va_start(vargs
, format
);
517 string
= PyString_FromFormatV(format
, vargs
);
518 PyErr_SetObject(exception
, string
);
526 PyErr_NewException(char *name
, PyObject
*base
, PyObject
*dict
)
529 PyObject
*modulename
= NULL
;
530 PyObject
*classname
= NULL
;
531 PyObject
*mydict
= NULL
;
532 PyObject
*bases
= NULL
;
533 PyObject
*result
= NULL
;
534 dot
= strrchr(name
, '.');
536 PyErr_SetString(PyExc_SystemError
,
537 "PyErr_NewException: name must be module.class");
541 base
= PyExc_Exception
;
543 dict
= mydict
= PyDict_New();
547 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
548 modulename
= PyString_FromStringAndSize(name
, (int)(dot
-name
));
549 if (modulename
== NULL
)
551 if (PyDict_SetItemString(dict
, "__module__", modulename
) != 0)
554 classname
= PyString_FromString(dot
+1);
555 if (classname
== NULL
)
557 bases
= PyTuple_Pack(1, base
);
560 result
= PyClass_New(bases
, dict
, classname
);
564 Py_XDECREF(classname
);
565 Py_XDECREF(modulename
);
569 /* Call when an exception has occurred but there is no way for Python
570 to handle it. Examples: exception in __del__ or during GC. */
572 PyErr_WriteUnraisable(PyObject
*obj
)
574 PyObject
*f
, *t
, *v
, *tb
;
575 PyErr_Fetch(&t
, &v
, &tb
);
576 f
= PySys_GetObject("stderr");
578 PyFile_WriteString("Exception ", f
);
580 char* className
= PyExceptionClass_Name(t
);
581 PyObject
* moduleName
=
582 PyObject_GetAttrString(t
, "__module__");
584 if (moduleName
== NULL
)
585 PyFile_WriteString("<unknown>", f
);
587 char* modstr
= PyString_AsString(moduleName
);
590 PyFile_WriteString(modstr
, f
);
591 PyFile_WriteString(".", f
);
594 if (className
== NULL
)
595 PyFile_WriteString("<unknown>", f
);
597 PyFile_WriteString(className
, f
);
598 if (v
&& v
!= Py_None
) {
599 PyFile_WriteString(": ", f
);
600 PyFile_WriteObject(v
, f
, 0);
603 PyFile_WriteString(" in ", f
);
604 PyFile_WriteObject(obj
, f
, 0);
605 PyFile_WriteString(" ignored\n", f
);
606 PyErr_Clear(); /* Just in case */
613 extern PyObject
*PyModule_GetWarningsModule(void);
615 /* Function to issue a warning message; may raise an exception. */
617 PyErr_Warn(PyObject
*category
, char *message
)
619 PyObject
*dict
, *func
= NULL
;
620 PyObject
*warnings_module
= PyModule_GetWarningsModule();
622 if (warnings_module
!= NULL
) {
623 dict
= PyModule_GetDict(warnings_module
);
624 func
= PyDict_GetItemString(dict
, "warn");
627 PySys_WriteStderr("warning: %s\n", message
);
631 PyObject
*args
, *res
;
633 if (category
== NULL
)
634 category
= PyExc_RuntimeWarning
;
635 args
= Py_BuildValue("(sO)", message
, category
);
638 res
= PyEval_CallObject(func
, args
);
648 /* Warning with explicit origin */
650 PyErr_WarnExplicit(PyObject
*category
, const char *message
,
651 const char *filename
, int lineno
,
652 const char *module
, PyObject
*registry
)
654 PyObject
*mod
, *dict
, *func
= NULL
;
656 mod
= PyImport_ImportModule("warnings");
658 dict
= PyModule_GetDict(mod
);
659 func
= PyDict_GetItemString(dict
, "warn_explicit");
663 PySys_WriteStderr("warning: %s\n", message
);
667 PyObject
*args
, *res
;
669 if (category
== NULL
)
670 category
= PyExc_RuntimeWarning
;
671 if (registry
== NULL
)
673 args
= Py_BuildValue("(sOsizO)", message
, category
,
674 filename
, lineno
, module
, registry
);
677 res
= PyEval_CallObject(func
, args
);
687 /* Set file and line information for the current exception.
688 If the exception is not a SyntaxError, also sets additional attributes
689 to make printing of exceptions believe it is a syntax error. */
692 PyErr_SyntaxLocation(const char *filename
, int lineno
)
694 PyObject
*exc
, *v
, *tb
, *tmp
;
696 /* add attributes for the line number and filename for the error */
697 PyErr_Fetch(&exc
, &v
, &tb
);
698 PyErr_NormalizeException(&exc
, &v
, &tb
);
699 /* XXX check that it is, indeed, a syntax error */
700 tmp
= PyInt_FromLong(lineno
);
704 if (PyObject_SetAttrString(v
, "lineno", tmp
))
708 if (filename
!= NULL
) {
709 tmp
= PyString_FromString(filename
);
713 if (PyObject_SetAttrString(v
, "filename", tmp
))
718 tmp
= PyErr_ProgramText(filename
, lineno
);
720 PyObject_SetAttrString(v
, "text", tmp
);
724 if (PyObject_SetAttrString(v
, "offset", Py_None
)) {
727 if (exc
!= PyExc_SyntaxError
) {
728 if (!PyObject_HasAttrString(v
, "msg")) {
729 tmp
= PyObject_Str(v
);
731 if (PyObject_SetAttrString(v
, "msg", tmp
))
738 if (!PyObject_HasAttrString(v
, "print_file_and_line")) {
739 if (PyObject_SetAttrString(v
, "print_file_and_line",
744 PyErr_Restore(exc
, v
, tb
);
747 /* com_fetch_program_text will attempt to load the line of text that
748 the exception refers to. If it fails, it will return NULL but will
749 not set an exception.
751 XXX The functionality of this function is quite similar to the
752 functionality in tb_displayline() in traceback.c.
756 PyErr_ProgramText(const char *filename
, int lineno
)
762 if (filename
== NULL
|| *filename
== '\0' || lineno
<= 0)
764 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
767 for (i
= 0; i
< lineno
; i
++) {
768 char *pLastChar
= &linebuf
[sizeof(linebuf
) - 2];
771 if (Py_UniversalNewlineFgets(linebuf
, sizeof linebuf
, fp
, NULL
) == NULL
)
773 /* fgets read *something*; if it didn't get as
774 far as pLastChar, it must have found a newline
775 or hit the end of the file; if pLastChar is \n,
776 it obviously found a newline; else we haven't
777 yet seen a newline, so must continue */
778 } while (*pLastChar
!= '\0' && *pLastChar
!= '\n');
783 while (*p
== ' ' || *p
== '\t' || *p
== '\014')
785 return PyString_FromString(p
);