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
;
137 /* There was no exception, so nothing to do. */
141 /* If PyErr_SetNone() was used, the value will have been actually
149 if (PyExceptionInstance_Check(value
))
150 inclass
= PyExceptionInstance_Class(value
);
152 /* Normalize the exception so that if the type is a class, the
153 value will be an instance.
155 if (PyExceptionClass_Check(type
)) {
156 /* if the value was not an instance, or is not an instance
157 whose class is (or is derived from) type, then use the
158 value as an argument to instantiation of the type
161 if (!inclass
|| !PyObject_IsSubclass(inclass
, type
)) {
162 PyObject
*args
, *res
;
164 if (value
== Py_None
)
165 args
= PyTuple_New(0);
166 else if (PyTuple_Check(value
)) {
171 args
= PyTuple_Pack(1, value
);
175 res
= PyEval_CallObject(type
, args
);
182 /* if the class of the instance doesn't exactly match the
183 class of the type, believe the instance
185 else if (inclass
!= type
) {
197 /* If the new exception doesn't set a traceback and the old
198 exception had a traceback, use the old traceback for the
199 new exception. It's better than nothing.
202 PyErr_Fetch(exc
, val
, tb
);
203 if (initial_tb
!= NULL
) {
207 Py_DECREF(initial_tb
);
209 /* normalize recursively */
210 PyErr_NormalizeException(exc
, val
, tb
);
215 PyErr_Fetch(PyObject
**p_type
, PyObject
**p_value
, PyObject
**p_traceback
)
217 PyThreadState
*tstate
= PyThreadState_GET();
219 *p_type
= tstate
->curexc_type
;
220 *p_value
= tstate
->curexc_value
;
221 *p_traceback
= tstate
->curexc_traceback
;
223 tstate
->curexc_type
= NULL
;
224 tstate
->curexc_value
= NULL
;
225 tstate
->curexc_traceback
= NULL
;
231 PyErr_Restore(NULL
, NULL
, NULL
);
234 /* Convenience functions to set a type error exception and return 0 */
237 PyErr_BadArgument(void)
239 PyErr_SetString(PyExc_TypeError
,
240 "bad argument type for built-in operation");
247 if (PyErr_ExceptionMatches(PyExc_MemoryError
))
248 /* already current */
251 /* raise the pre-allocated instance if it still exists */
252 if (PyExc_MemoryErrorInst
)
253 PyErr_SetObject(PyExc_MemoryError
, PyExc_MemoryErrorInst
);
255 /* this will probably fail since there's no memory and hee,
256 hee, we have to instantiate this class
258 PyErr_SetNone(PyExc_MemoryError
);
264 PyErr_SetFromErrnoWithFilenameObject(PyObject
*exc
, PyObject
*filenameObject
)
274 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
277 if (i
== EINTR
&& PyErr_CheckSignals())
281 rerrstr(errbuf
, sizeof errbuf
);
285 s
= "Error"; /* Sometimes errno didn't get set */
291 /* Note that the Win32 errors do not lineup with the
292 errno error. So if the error is in the MSVC error
293 table, we use it, otherwise we assume it really _is_
296 if (i
> 0 && i
< _sys_nerr
) {
300 int len
= FormatMessage(
301 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
302 FORMAT_MESSAGE_FROM_SYSTEM
|
303 FORMAT_MESSAGE_IGNORE_INSERTS
,
304 NULL
, /* no message source */
306 MAKELANGID(LANG_NEUTRAL
,
308 /* Default language */
310 0, /* size not used */
313 /* Only ever seen this in out-of-mem
315 sprintf(s_small_buf
, "Windows Error 0x%X", i
);
320 /* remove trailing cr/lf and dots */
321 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
326 #endif /* Unix/Windows */
328 if (filenameObject
!= NULL
)
329 v
= Py_BuildValue("(isO)", i
, s
, filenameObject
);
331 v
= Py_BuildValue("(is)", i
, s
);
333 PyErr_SetObject(exc
, v
);
344 PyErr_SetFromErrnoWithFilename(PyObject
*exc
, char *filename
)
346 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
347 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
352 #ifdef Py_WIN_WIDE_FILENAMES
354 PyErr_SetFromErrnoWithUnicodeFilename(PyObject
*exc
, Py_UNICODE
*filename
)
356 PyObject
*name
= filename
?
357 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
359 PyObject
*result
= PyErr_SetFromErrnoWithFilenameObject(exc
, name
);
363 #endif /* Py_WIN_WIDE_FILENAMES */
366 PyErr_SetFromErrno(PyObject
*exc
)
368 return PyErr_SetFromErrnoWithFilenameObject(exc
, NULL
);
372 /* Windows specific error code handling */
373 PyObject
*PyErr_SetExcFromWindowsErrWithFilenameObject(
376 PyObject
*filenameObject
)
380 char *s_buf
= NULL
; /* Free via LocalFree */
381 char s_small_buf
[28]; /* Room for "Windows Error 0xFFFFFFFF" */
383 DWORD err
= (DWORD
)ierr
;
384 if (err
==0) err
= GetLastError();
386 /* Error API error */
387 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
388 FORMAT_MESSAGE_FROM_SYSTEM
|
389 FORMAT_MESSAGE_IGNORE_INSERTS
,
390 NULL
, /* no message source */
392 MAKELANGID(LANG_NEUTRAL
,
393 SUBLANG_DEFAULT
), /* Default language */
395 0, /* size not used */
398 /* Only seen this in out of mem situations */
399 sprintf(s_small_buf
, "Windows Error 0x%X", err
);
404 /* remove trailing cr/lf and dots */
405 while (len
> 0 && (s
[len
-1] <= ' ' || s
[len
-1] == '.'))
408 if (filenameObject
!= NULL
)
409 v
= Py_BuildValue("(isO)", err
, s
, filenameObject
);
411 v
= Py_BuildValue("(is)", err
, s
);
413 PyErr_SetObject(exc
, v
);
420 PyObject
*PyErr_SetExcFromWindowsErrWithFilename(
423 const char *filename
)
425 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
426 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
433 #ifdef Py_WIN_WIDE_FILENAMES
434 PyObject
*PyErr_SetExcFromWindowsErrWithUnicodeFilename(
437 const Py_UNICODE
*filename
)
439 PyObject
*name
= filename
?
440 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
442 PyObject
*ret
= PyErr_SetExcFromWindowsErrWithFilenameObject(exc
,
448 #endif /* Py_WIN_WIDE_FILENAMES */
450 PyObject
*PyErr_SetExcFromWindowsErr(PyObject
*exc
, int ierr
)
452 return PyErr_SetExcFromWindowsErrWithFilename(exc
, ierr
, NULL
);
455 PyObject
*PyErr_SetFromWindowsErr(int ierr
)
457 return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError
,
460 PyObject
*PyErr_SetFromWindowsErrWithFilename(
462 const char *filename
)
464 PyObject
*name
= filename
? PyString_FromString(filename
) : NULL
;
465 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
472 #ifdef Py_WIN_WIDE_FILENAMES
473 PyObject
*PyErr_SetFromWindowsErrWithUnicodeFilename(
475 const Py_UNICODE
*filename
)
477 PyObject
*name
= filename
?
478 PyUnicode_FromUnicode(filename
, wcslen(filename
)) :
480 PyObject
*result
= PyErr_SetExcFromWindowsErrWithFilenameObject(
486 #endif /* Py_WIN_WIDE_FILENAMES */
487 #endif /* MS_WINDOWS */
490 _PyErr_BadInternalCall(char *filename
, int lineno
)
492 PyErr_Format(PyExc_SystemError
,
493 "%s:%d: bad argument to internal function",
497 /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
498 export the entry point for existing object code: */
499 #undef PyErr_BadInternalCall
501 PyErr_BadInternalCall(void)
503 PyErr_Format(PyExc_SystemError
,
504 "bad argument to internal function");
506 #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
511 PyErr_Format(PyObject
*exception
, const char *format
, ...)
516 #ifdef HAVE_STDARG_PROTOTYPES
517 va_start(vargs
, format
);
522 string
= PyString_FromFormatV(format
, vargs
);
523 PyErr_SetObject(exception
, string
);
532 PyErr_NewException(char *name
, PyObject
*base
, PyObject
*dict
)
535 PyObject
*modulename
= NULL
;
536 PyObject
*classname
= NULL
;
537 PyObject
*mydict
= NULL
;
538 PyObject
*bases
= NULL
;
539 PyObject
*result
= NULL
;
540 dot
= strrchr(name
, '.');
542 PyErr_SetString(PyExc_SystemError
,
543 "PyErr_NewException: name must be module.class");
547 base
= PyExc_Exception
;
549 dict
= mydict
= PyDict_New();
553 if (PyDict_GetItemString(dict
, "__module__") == NULL
) {
554 modulename
= PyString_FromStringAndSize(name
,
555 (Py_ssize_t
)(dot
-name
));
556 if (modulename
== NULL
)
558 if (PyDict_SetItemString(dict
, "__module__", modulename
) != 0)
561 if (PyTuple_Check(base
)) {
563 /* INCREF as we create a new ref in the else branch */
566 bases
= PyTuple_Pack(1, base
);
570 /* Create a real new-style class. */
571 result
= PyObject_CallFunction((PyObject
*)&PyType_Type
, "sOO",
576 Py_XDECREF(classname
);
577 Py_XDECREF(modulename
);
581 /* Call when an exception has occurred but there is no way for Python
582 to handle it. Examples: exception in __del__ or during GC. */
584 PyErr_WriteUnraisable(PyObject
*obj
)
586 PyObject
*f
, *t
, *v
, *tb
;
587 PyErr_Fetch(&t
, &v
, &tb
);
588 f
= PySys_GetObject("stderr");
590 PyFile_WriteString("Exception ", f
);
592 PyObject
* moduleName
;
593 char* className
= PyExceptionClass_Name(t
);
595 if (className
!= NULL
) {
596 char *dot
= strrchr(className
, '.');
601 moduleName
= PyObject_GetAttrString(t
, "__module__");
602 if (moduleName
== NULL
)
603 PyFile_WriteString("<unknown>", f
);
605 char* modstr
= PyString_AsString(moduleName
);
608 PyFile_WriteString(modstr
, f
);
609 PyFile_WriteString(".", f
);
612 if (className
== NULL
)
613 PyFile_WriteString("<unknown>", f
);
615 PyFile_WriteString(className
, f
);
616 if (v
&& v
!= Py_None
) {
617 PyFile_WriteString(": ", f
);
618 PyFile_WriteObject(v
, f
, 0);
620 Py_XDECREF(moduleName
);
622 PyFile_WriteString(" in ", f
);
623 PyFile_WriteObject(obj
, f
, 0);
624 PyFile_WriteString(" ignored\n", f
);
625 PyErr_Clear(); /* Just in case */
632 extern PyObject
*PyModule_GetWarningsModule(void);
634 /* Function to issue a warning message; may raise an exception. */
636 PyErr_WarnEx(PyObject
*category
, const char *message
, Py_ssize_t stack_level
)
638 PyObject
*dict
, *func
= NULL
;
639 PyObject
*warnings_module
= PyModule_GetWarningsModule();
641 if (warnings_module
!= NULL
) {
642 dict
= PyModule_GetDict(warnings_module
);
643 func
= PyDict_GetItemString(dict
, "warn");
646 PySys_WriteStderr("warning: %s\n", message
);
652 if (category
== NULL
)
653 category
= PyExc_RuntimeWarning
;
654 res
= PyObject_CallFunction(func
, "sOn",
655 message
, category
, stack_level
);
663 /* PyErr_Warn is only for backwards compatability and will be removed.
664 Use PyErr_WarnEx instead. */
669 PyErr_Warn(PyObject
*category
, char *message
)
671 return PyErr_WarnEx(category
, message
, 1);
674 /* Warning with explicit origin */
676 PyErr_WarnExplicit(PyObject
*category
, const char *message
,
677 const char *filename
, int lineno
,
678 const char *module
, PyObject
*registry
)
680 PyObject
*mod
, *dict
, *func
= NULL
;
682 mod
= PyImport_ImportModule("warnings");
684 dict
= PyModule_GetDict(mod
);
685 func
= PyDict_GetItemString(dict
, "warn_explicit");
689 PySys_WriteStderr("warning: %s\n", message
);
695 if (category
== NULL
)
696 category
= PyExc_RuntimeWarning
;
697 if (registry
== NULL
)
699 res
= PyObject_CallFunction(func
, "sOsizO", message
, category
,
700 filename
, lineno
, module
, registry
);
709 /* Set file and line information for the current exception.
710 If the exception is not a SyntaxError, also sets additional attributes
711 to make printing of exceptions believe it is a syntax error. */
714 PyErr_SyntaxLocation(const char *filename
, int lineno
)
716 PyObject
*exc
, *v
, *tb
, *tmp
;
718 /* add attributes for the line number and filename for the error */
719 PyErr_Fetch(&exc
, &v
, &tb
);
720 PyErr_NormalizeException(&exc
, &v
, &tb
);
721 /* XXX check that it is, indeed, a syntax error. It might not
723 tmp
= PyInt_FromLong(lineno
);
727 if (PyObject_SetAttrString(v
, "lineno", tmp
))
731 if (filename
!= NULL
) {
732 tmp
= PyString_FromString(filename
);
736 if (PyObject_SetAttrString(v
, "filename", tmp
))
741 tmp
= PyErr_ProgramText(filename
, lineno
);
743 if (PyObject_SetAttrString(v
, "text", tmp
))
748 if (PyObject_SetAttrString(v
, "offset", Py_None
)) {
751 if (exc
!= PyExc_SyntaxError
) {
752 if (!PyObject_HasAttrString(v
, "msg")) {
753 tmp
= PyObject_Str(v
);
755 if (PyObject_SetAttrString(v
, "msg", tmp
))
762 if (!PyObject_HasAttrString(v
, "print_file_and_line")) {
763 if (PyObject_SetAttrString(v
, "print_file_and_line",
768 PyErr_Restore(exc
, v
, tb
);
771 /* com_fetch_program_text will attempt to load the line of text that
772 the exception refers to. If it fails, it will return NULL but will
773 not set an exception.
775 XXX The functionality of this function is quite similar to the
776 functionality in tb_displayline() in traceback.c.
780 PyErr_ProgramText(const char *filename
, int lineno
)
786 if (filename
== NULL
|| *filename
== '\0' || lineno
<= 0)
788 fp
= fopen(filename
, "r" PY_STDIOTEXTMODE
);
791 for (i
= 0; i
< lineno
; i
++) {
792 char *pLastChar
= &linebuf
[sizeof(linebuf
) - 2];
795 if (Py_UniversalNewlineFgets(linebuf
, sizeof linebuf
, fp
, NULL
) == NULL
)
797 /* fgets read *something*; if it didn't get as
798 far as pLastChar, it must have found a newline
799 or hit the end of the file; if pLastChar is \n,
800 it obviously found a newline; else we haven't
801 yet seen a newline, so must continue */
802 } while (*pLastChar
!= '\0' && *pLastChar
!= '\n');
807 while (*p
== ' ' || *p
== '\t' || *p
== '\014')
809 return PyString_FromString(p
);