1 /* This module provides the suite of standard class-based exceptions for
2 * Python's builtin module. This is a complete C implementation of what,
3 * in Python 1.5.2, was contained in the exceptions.py module. The problem
4 * there was that if exceptions.py could not be imported for some reason,
5 * the entire interpreter would abort.
7 * By moving the exceptions into C and statically linking, we can guarantee
8 * that the standard exceptions will always be available.
11 * 98-08-19 fl created (for pyexe)
12 * 00-02-08 fl updated for 1.5.2
13 * 26-May-2000 baw vetted for Python 1.6
15 * written by Fredrik Lundh
16 * modifications, additions, cleanups, and proofreading by Barry Warsaw
18 * Copyright (c) 1998-2000 by Secret Labs AB. All rights reserved.
24 /* Caution: MS Visual C++ 6 errors if a single string literal exceeds
25 * 2Kb. So the module docstring has been broken roughly in half, using
26 * compile-time literal concatenation.
30 "Python's standard exception class hierarchy.\n\
32 Before Python 1.5, the standard exceptions were all simple string objects.\n\
33 In Python 1.5, the standard exceptions were converted to classes organized\n\
34 into a relatively flat hierarchy. String-based standard exceptions were\n\
35 optional, or used as a fallback if some problem occurred while importing\n\
36 the exception module. With Python 1.6, optional string-based standard\n\
37 exceptions were removed (along with the -X command line flag).\n\
39 The class exceptions were implemented in such a way as to be almost\n\
40 completely backward compatible. Some tricky uses of IOError could\n\
41 potentially have broken, but by Python 1.6, all of these should have\n\
42 been fixed. As of Python 1.6, the class-based standard exceptions are\n\
43 now implemented in C, and are guaranteed to exist in the Python\n\
46 Here is a rundown of the class hierarchy. The classes found here are\n\
47 inserted into both the exceptions module and the `built-in' module. It is\n\
48 recommended that user defined class based exceptions be derived from the\n\
49 `Exception' class, although this is currently not enforced.\n"
50 /* keep string pieces "small" */
57 | +-- KeyboardInterrupt\n\
59 | +-- EnvironmentError\n\
64 | | +-- WindowsError\n\
69 | | +-- NotImplementedError\n\
73 | | +-- UnboundLocalError\n\
75 | +-- AttributeError\n\
78 | | +-- IndentationError\n\
83 | +-- AssertionError\n\
89 | +-- ArithmeticError\n\
91 | | +-- OverflowError\n\
92 | | +-- ZeroDivisionError\n\
93 | | +-- FloatingPointError\n\
97 | | +-- UnicodeError\n\
105 +-- DeprecationWarning\n\
110 /* Helper function for populating a dictionary with method wrappers. */
112 populate_methods(PyObject
*klass
, PyObject
*dict
, PyMethodDef
*methods
)
117 while (methods
->ml_name
) {
118 /* get a wrapper for the built-in function */
119 PyObject
*func
= PyCFunction_New(methods
, NULL
);
126 /* turn the function into an unbound method */
127 if (!(meth
= PyMethod_New(func
, NULL
, klass
))) {
132 /* add method to dictionary */
133 status
= PyDict_SetItemString(dict
, methods
->ml_name
, meth
);
137 /* stop now if an error occurred, otherwise do the next method */
148 /* This function is used to create all subsequent exception classes. */
150 make_class(PyObject
**klass
, PyObject
*base
,
151 char *name
, PyMethodDef
*methods
,
154 PyObject
*dict
= PyDict_New();
155 PyObject
*str
= NULL
;
161 /* If an error occurs from here on, goto finally instead of explicitly
166 if (!(str
= PyString_FromString(docstr
)))
168 if (PyDict_SetItemString(dict
, "__doc__", str
))
172 if (!(*klass
= PyErr_NewException(name
, base
, dict
)))
175 if (populate_methods(*klass
, dict
, methods
)) {
190 /* Use this for *args signatures, otherwise just use PyArg_ParseTuple() */
192 get_self(PyObject
*args
)
194 PyObject
*self
= PyTuple_GetItem(args
, 0);
196 /* Watch out for being called to early in the bootstrapping process */
197 if (PyExc_TypeError
) {
198 PyErr_SetString(PyExc_TypeError
,
199 "unbound method must be called with instance as first argument");
208 /* Notes on bootstrapping the exception classes.
210 * First thing we create is the base class for all exceptions, called
211 * appropriately enough: Exception. Creation of this class makes no
212 * assumptions about the existence of any other exception class -- except
213 * for TypeError, which can conditionally exist.
215 * Next, StandardError is created (which is quite simple) followed by
216 * TypeError, because the instantiation of other exceptions can potentially
217 * throw a TypeError. Once these exceptions are created, all the others
218 * can be created in any order. See the static exctable below for the
219 * explicit bootstrap order.
221 * All classes after Exception can be created using PyErr_NewException().
225 Exception__doc__
[] = "Common base class for all exceptions.";
229 Exception__init__(PyObject
*self
, PyObject
*args
)
233 if (!(self
= get_self(args
)))
236 /* set args attribute */
237 /* XXX size is only a hint */
238 args
= PySequence_GetSlice(args
, 1, PySequence_Size(args
));
241 status
= PyObject_SetAttrString(self
, "args", args
);
252 Exception__str__(PyObject
*self
, PyObject
*args
)
256 if (!PyArg_ParseTuple(args
, "O:__str__", &self
))
259 args
= PyObject_GetAttrString(self
, "args");
263 switch (PySequence_Size(args
)) {
265 out
= PyString_FromString("");
269 PyObject
*tmp
= PySequence_GetItem(args
, 0);
271 out
= PyObject_Str(tmp
);
279 out
= PyObject_Str(args
);
289 Exception__getitem__(PyObject
*self
, PyObject
*args
)
294 if (!PyArg_ParseTuple(args
, "OO:__getitem__", &self
, &index
))
297 args
= PyObject_GetAttrString(self
, "args");
301 out
= PyObject_GetItem(args
, index
);
308 Exception_methods
[] = {
309 /* methods for the Exception class */
310 { "__getitem__", Exception__getitem__
, METH_VARARGS
},
311 { "__str__", Exception__str__
, METH_VARARGS
},
312 { "__init__", Exception__init__
, METH_VARARGS
},
318 make_Exception(char *modulename
)
320 PyObject
*dict
= PyDict_New();
321 PyObject
*str
= NULL
;
322 PyObject
*name
= NULL
;
328 /* If an error occurs from here on, goto finally instead of explicitly
332 if (!(str
= PyString_FromString(modulename
)))
334 if (PyDict_SetItemString(dict
, "__module__", str
))
337 if (!(str
= PyString_FromString(Exception__doc__
)))
339 if (PyDict_SetItemString(dict
, "__doc__", str
))
342 if (!(name
= PyString_FromString("Exception")))
345 if (!(PyExc_Exception
= PyClass_New(NULL
, dict
, name
)))
348 /* Now populate the dictionary with the method suite */
349 if (populate_methods(PyExc_Exception
, dict
, Exception_methods
))
350 /* Don't need to reclaim PyExc_Exception here because that'll
351 * happen during interpreter shutdown.
367 StandardError__doc__
[] = "Base class for all standard Python exceptions.";
370 TypeError__doc__
[] = "Inappropriate argument type.";
375 SystemExit__doc__
[] = "Request to exit from the interpreter.";
379 SystemExit__init__(PyObject
*self
, PyObject
*args
)
384 if (!(self
= get_self(args
)))
387 /* Set args attribute. */
388 if (!(args
= PySequence_GetSlice(args
, 1, PySequence_Size(args
))))
391 status
= PyObject_SetAttrString(self
, "args", args
);
397 /* set code attribute */
398 switch (PySequence_Size(args
)) {
404 code
= PySequence_GetItem(args
, 0);
412 status
= PyObject_SetAttrString(self
, "code", code
);
423 PyMethodDef SystemExit_methods
[] = {
424 { "__init__", SystemExit__init__
, METH_VARARGS
},
431 KeyboardInterrupt__doc__
[] = "Program interrupted by user.";
434 ImportError__doc__
[] =
435 "Import can't find module, or can't find name in module.";
440 EnvironmentError__doc__
[] = "Base class for I/O related errors.";
444 EnvironmentError__init__(PyObject
*self
, PyObject
*args
)
446 PyObject
*item0
= NULL
;
447 PyObject
*item1
= NULL
;
448 PyObject
*item2
= NULL
;
449 PyObject
*subslice
= NULL
;
450 PyObject
*rtnval
= NULL
;
452 if (!(self
= get_self(args
)))
455 if (!(args
= PySequence_GetSlice(args
, 1, PySequence_Size(args
))))
458 if (PyObject_SetAttrString(self
, "args", args
) ||
459 PyObject_SetAttrString(self
, "errno", Py_None
) ||
460 PyObject_SetAttrString(self
, "strerror", Py_None
) ||
461 PyObject_SetAttrString(self
, "filename", Py_None
))
466 switch (PySequence_Size(args
)) {
468 /* Where a function has a single filename, such as open() or some
469 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
470 * called, giving a third argument which is the filename. But, so
471 * that old code using in-place unpacking doesn't break, e.g.:
473 * except IOError, (errno, strerror):
475 * we hack args so that it only contains two items. This also
476 * means we need our own __str__() which prints out the filename
477 * when it was supplied.
479 item0
= PySequence_GetItem(args
, 0);
480 item1
= PySequence_GetItem(args
, 1);
481 item2
= PySequence_GetItem(args
, 2);
482 if (!item0
|| !item1
|| !item2
)
485 if (PyObject_SetAttrString(self
, "errno", item0
) ||
486 PyObject_SetAttrString(self
, "strerror", item1
) ||
487 PyObject_SetAttrString(self
, "filename", item2
))
492 subslice
= PySequence_GetSlice(args
, 0, 2);
493 if (!subslice
|| PyObject_SetAttrString(self
, "args", subslice
))
498 /* Used when PyErr_SetFromErrno() is called and no filename
501 item0
= PySequence_GetItem(args
, 0);
502 item1
= PySequence_GetItem(args
, 1);
503 if (!item0
|| !item1
)
506 if (PyObject_SetAttrString(self
, "errno", item0
) ||
507 PyObject_SetAttrString(self
, "strerror", item1
))
522 Py_XDECREF(subslice
);
528 EnvironmentError__str__(PyObject
*self
, PyObject
*args
)
530 PyObject
*originalself
= self
;
534 PyObject
*rtnval
= NULL
;
536 if (!PyArg_ParseTuple(args
, "O:__str__", &self
))
539 filename
= PyObject_GetAttrString(self
, "filename");
540 serrno
= PyObject_GetAttrString(self
, "errno");
541 strerror
= PyObject_GetAttrString(self
, "strerror");
542 if (!filename
|| !serrno
|| !strerror
)
545 if (filename
!= Py_None
) {
546 PyObject
*fmt
= PyString_FromString("[Errno %s] %s: %s");
547 PyObject
*repr
= PyObject_Repr(filename
);
548 PyObject
*tuple
= PyTuple_New(3);
550 if (!fmt
|| !repr
|| !tuple
) {
557 PyTuple_SET_ITEM(tuple
, 0, serrno
);
558 PyTuple_SET_ITEM(tuple
, 1, strerror
);
559 PyTuple_SET_ITEM(tuple
, 2, repr
);
561 rtnval
= PyString_Format(fmt
, tuple
);
565 /* already freed because tuple owned only reference */
569 else if (PyObject_IsTrue(serrno
) && PyObject_IsTrue(strerror
)) {
570 PyObject
*fmt
= PyString_FromString("[Errno %s] %s");
571 PyObject
*tuple
= PyTuple_New(2);
573 if (!fmt
|| !tuple
) {
579 PyTuple_SET_ITEM(tuple
, 0, serrno
);
580 PyTuple_SET_ITEM(tuple
, 1, strerror
);
582 rtnval
= PyString_Format(fmt
, tuple
);
586 /* already freed because tuple owned only reference */
591 /* The original Python code said:
593 * return StandardError.__str__(self)
595 * but there is no StandardError__str__() function; we happen to
596 * know that's just a pass through to Exception__str__().
598 rtnval
= Exception__str__(originalself
, args
);
601 Py_XDECREF(filename
);
603 Py_XDECREF(strerror
);
609 PyMethodDef EnvironmentError_methods
[] = {
610 {"__init__", EnvironmentError__init__
, METH_VARARGS
},
611 {"__str__", EnvironmentError__str__
, METH_VARARGS
},
619 IOError__doc__
[] = "I/O operation failed.";
622 OSError__doc__
[] = "OS system call failed.";
626 WindowsError__doc__
[] = "MS-Windows OS system call failed.";
627 #endif /* MS_WINDOWS */
630 EOFError__doc__
[] = "Read beyond end of file.";
633 RuntimeError__doc__
[] = "Unspecified run-time error.";
636 NotImplementedError__doc__
[] =
637 "Method or function hasn't been implemented yet.";
640 NameError__doc__
[] = "Name not found globally.";
643 UnboundLocalError__doc__
[] =
644 "Local name referenced but not bound to a value.";
647 AttributeError__doc__
[] = "Attribute not found.";
652 SyntaxError__doc__
[] = "Invalid syntax.";
656 SyntaxError__classinit__(PyObject
*klass
)
659 PyObject
*emptystring
= PyString_FromString("");
661 /* Additional class-creation time initializations */
663 PyObject_SetAttrString(klass
, "msg", emptystring
) ||
664 PyObject_SetAttrString(klass
, "filename", Py_None
) ||
665 PyObject_SetAttrString(klass
, "lineno", Py_None
) ||
666 PyObject_SetAttrString(klass
, "offset", Py_None
) ||
667 PyObject_SetAttrString(klass
, "text", Py_None
))
671 Py_XDECREF(emptystring
);
677 SyntaxError__init__(PyObject
*self
, PyObject
*args
)
679 PyObject
*rtnval
= NULL
;
682 if (!(self
= get_self(args
)))
685 if (!(args
= PySequence_GetSlice(args
, 1, PySequence_Size(args
))))
688 if (PyObject_SetAttrString(self
, "args", args
))
691 lenargs
= PySequence_Size(args
);
693 PyObject
*item0
= PySequence_GetItem(args
, 0);
698 status
= PyObject_SetAttrString(self
, "msg", item0
);
704 PyObject
*info
= PySequence_GetItem(args
, 1);
705 PyObject
*filename
= NULL
, *lineno
= NULL
;
706 PyObject
*offset
= NULL
, *text
= NULL
;
712 filename
= PySequence_GetItem(info
, 0);
713 if (filename
!= NULL
) {
714 lineno
= PySequence_GetItem(info
, 1);
715 if (lineno
!= NULL
) {
716 offset
= PySequence_GetItem(info
, 2);
717 if (offset
!= NULL
) {
718 text
= PySequence_GetItem(info
, 3);
721 PyObject_SetAttrString(self
, "filename", filename
)
722 || PyObject_SetAttrString(self
, "lineno", lineno
)
723 || PyObject_SetAttrString(self
, "offset", offset
)
724 || PyObject_SetAttrString(self
, "text", text
);
747 /* This is called "my_basename" instead of just "basename" to avoid name
748 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
749 defined, and Python does define that. */
751 my_basename(char *name
)
758 while (*cp
!= '\0') {
768 SyntaxError__str__(PyObject
*self
, PyObject
*args
)
772 PyObject
*filename
, *lineno
, *result
;
774 if (!PyArg_ParseTuple(args
, "O:__str__", &self
))
777 if (!(msg
= PyObject_GetAttrString(self
, "msg")))
780 str
= PyObject_Str(msg
);
784 /* XXX -- do all the additional formatting with filename and
787 if (PyString_Check(str
)) {
788 int have_filename
= 0;
792 if ((filename
= PyObject_GetAttrString(self
, "filename")) != NULL
)
793 have_filename
= PyString_Check(filename
);
797 if ((lineno
= PyObject_GetAttrString(self
, "lineno")) != NULL
)
798 have_lineno
= PyInt_Check(lineno
);
802 if (have_filename
|| have_lineno
) {
803 int bufsize
= PyString_GET_SIZE(str
) + 64;
805 bufsize
+= PyString_GET_SIZE(filename
);
807 buffer
= PyMem_Malloc(bufsize
);
808 if (buffer
!= NULL
) {
809 if (have_filename
&& have_lineno
)
810 sprintf(buffer
, "%s (%s, line %ld)",
811 PyString_AS_STRING(str
),
812 my_basename(PyString_AS_STRING(filename
)),
813 PyInt_AsLong(lineno
));
814 else if (have_filename
)
815 sprintf(buffer
, "%s (%s)",
816 PyString_AS_STRING(str
),
817 my_basename(PyString_AS_STRING(filename
)));
818 else if (have_lineno
)
819 sprintf(buffer
, "%s (line %ld)",
820 PyString_AS_STRING(str
),
821 PyInt_AsLong(lineno
));
823 result
= PyString_FromString(buffer
);
832 Py_XDECREF(filename
);
839 PyMethodDef SyntaxError_methods
[] = {
840 {"__init__", SyntaxError__init__
, METH_VARARGS
},
841 {"__str__", SyntaxError__str__
, METH_VARARGS
},
847 /* Exception doc strings */
850 AssertionError__doc__
[] = "Assertion failed.";
853 LookupError__doc__
[] = "Base class for lookup errors.";
856 IndexError__doc__
[] = "Sequence index out of range.";
859 KeyError__doc__
[] = "Mapping key not found.";
862 ArithmeticError__doc__
[] = "Base class for arithmetic errors.";
865 OverflowError__doc__
[] = "Result too large to be represented.";
868 ZeroDivisionError__doc__
[] =
869 "Second argument to a division or modulo operation was zero.";
872 FloatingPointError__doc__
[] = "Floating point operation failed.";
875 ValueError__doc__
[] = "Inappropriate argument value (of correct type).";
878 UnicodeError__doc__
[] = "Unicode related error.";
881 SystemError__doc__
[] = "Internal error in the Python interpreter.\n\
883 Please report this to the Python maintainer, along with the traceback,\n\
884 the Python version, and the hardware/OS platform and version.";
887 MemoryError__doc__
[] = "Out of memory.";
890 IndentationError__doc__
[] = "Improper indentation.";
893 TabError__doc__
[] = "Improper mixture of spaces and tabs.";
895 /* Warning category docstrings */
898 Warning__doc__
[] = "Base class for warning categories.";
901 UserWarning__doc__
[] = "Base class for warnings generated by user code.";
904 DeprecationWarning__doc__
[] =
905 "Base class for warnings about deprecated features.";
908 SyntaxWarning__doc__
[] = "Base class for warnings about dubious syntax.";
911 RuntimeWarning__doc__
[] =
912 "Base class for warnings about dubious runtime behavior.";
916 /* module global functions */
917 static PyMethodDef functions
[] = {
924 /* Global C API defined exceptions */
926 PyObject
*PyExc_Exception
;
927 PyObject
*PyExc_StandardError
;
928 PyObject
*PyExc_ArithmeticError
;
929 PyObject
*PyExc_LookupError
;
931 PyObject
*PyExc_AssertionError
;
932 PyObject
*PyExc_AttributeError
;
933 PyObject
*PyExc_EOFError
;
934 PyObject
*PyExc_FloatingPointError
;
935 PyObject
*PyExc_EnvironmentError
;
936 PyObject
*PyExc_IOError
;
937 PyObject
*PyExc_OSError
;
938 PyObject
*PyExc_ImportError
;
939 PyObject
*PyExc_IndexError
;
940 PyObject
*PyExc_KeyError
;
941 PyObject
*PyExc_KeyboardInterrupt
;
942 PyObject
*PyExc_MemoryError
;
943 PyObject
*PyExc_NameError
;
944 PyObject
*PyExc_OverflowError
;
945 PyObject
*PyExc_RuntimeError
;
946 PyObject
*PyExc_NotImplementedError
;
947 PyObject
*PyExc_SyntaxError
;
948 PyObject
*PyExc_IndentationError
;
949 PyObject
*PyExc_TabError
;
950 PyObject
*PyExc_SystemError
;
951 PyObject
*PyExc_SystemExit
;
952 PyObject
*PyExc_UnboundLocalError
;
953 PyObject
*PyExc_UnicodeError
;
954 PyObject
*PyExc_TypeError
;
955 PyObject
*PyExc_ValueError
;
956 PyObject
*PyExc_ZeroDivisionError
;
958 PyObject
*PyExc_WindowsError
;
961 /* Pre-computed MemoryError instance. Best to create this as early as
962 * possibly and not wait until a MemoryError is actually raised!
964 PyObject
*PyExc_MemoryErrorInst
;
966 /* Predefined warning categories */
967 PyObject
*PyExc_Warning
;
968 PyObject
*PyExc_UserWarning
;
969 PyObject
*PyExc_DeprecationWarning
;
970 PyObject
*PyExc_SyntaxWarning
;
971 PyObject
*PyExc_RuntimeWarning
;
975 /* mapping between exception names and their PyObject ** */
979 PyObject
**base
; /* NULL == PyExc_StandardError */
981 PyMethodDef
*methods
;
982 int (*classinit
)(PyObject
*);
985 * The first three classes MUST appear in exactly this order
987 {"Exception", &PyExc_Exception
},
988 {"StandardError", &PyExc_StandardError
, &PyExc_Exception
,
989 StandardError__doc__
},
990 {"TypeError", &PyExc_TypeError
, 0, TypeError__doc__
},
992 * The rest appear in depth-first order of the hierarchy
994 {"SystemExit", &PyExc_SystemExit
, &PyExc_Exception
, SystemExit__doc__
,
996 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt
, 0, KeyboardInterrupt__doc__
},
997 {"ImportError", &PyExc_ImportError
, 0, ImportError__doc__
},
998 {"EnvironmentError", &PyExc_EnvironmentError
, 0, EnvironmentError__doc__
,
999 EnvironmentError_methods
},
1000 {"IOError", &PyExc_IOError
, &PyExc_EnvironmentError
, IOError__doc__
},
1001 {"OSError", &PyExc_OSError
, &PyExc_EnvironmentError
, OSError__doc__
},
1003 {"WindowsError", &PyExc_WindowsError
, &PyExc_OSError
,
1004 WindowsError__doc__
},
1005 #endif /* MS_WINDOWS */
1006 {"EOFError", &PyExc_EOFError
, 0, EOFError__doc__
},
1007 {"RuntimeError", &PyExc_RuntimeError
, 0, RuntimeError__doc__
},
1008 {"NotImplementedError", &PyExc_NotImplementedError
,
1009 &PyExc_RuntimeError
, NotImplementedError__doc__
},
1010 {"NameError", &PyExc_NameError
, 0, NameError__doc__
},
1011 {"UnboundLocalError", &PyExc_UnboundLocalError
, &PyExc_NameError
,
1012 UnboundLocalError__doc__
},
1013 {"AttributeError", &PyExc_AttributeError
, 0, AttributeError__doc__
},
1014 {"SyntaxError", &PyExc_SyntaxError
, 0, SyntaxError__doc__
,
1015 SyntaxError_methods
, SyntaxError__classinit__
},
1016 {"IndentationError", &PyExc_IndentationError
, &PyExc_SyntaxError
,
1017 IndentationError__doc__
},
1018 {"TabError", &PyExc_TabError
, &PyExc_IndentationError
,
1020 {"AssertionError", &PyExc_AssertionError
, 0, AssertionError__doc__
},
1021 {"LookupError", &PyExc_LookupError
, 0, LookupError__doc__
},
1022 {"IndexError", &PyExc_IndexError
, &PyExc_LookupError
,
1024 {"KeyError", &PyExc_KeyError
, &PyExc_LookupError
,
1026 {"ArithmeticError", &PyExc_ArithmeticError
, 0, ArithmeticError__doc__
},
1027 {"OverflowError", &PyExc_OverflowError
, &PyExc_ArithmeticError
,
1028 OverflowError__doc__
},
1029 {"ZeroDivisionError", &PyExc_ZeroDivisionError
, &PyExc_ArithmeticError
,
1030 ZeroDivisionError__doc__
},
1031 {"FloatingPointError", &PyExc_FloatingPointError
, &PyExc_ArithmeticError
,
1032 FloatingPointError__doc__
},
1033 {"ValueError", &PyExc_ValueError
, 0, ValueError__doc__
},
1034 {"UnicodeError", &PyExc_UnicodeError
, &PyExc_ValueError
, UnicodeError__doc__
},
1035 {"SystemError", &PyExc_SystemError
, 0, SystemError__doc__
},
1036 {"MemoryError", &PyExc_MemoryError
, 0, MemoryError__doc__
},
1037 /* Warning categories */
1038 {"Warning", &PyExc_Warning
, &PyExc_Exception
, Warning__doc__
},
1039 {"UserWarning", &PyExc_UserWarning
, &PyExc_Warning
, UserWarning__doc__
},
1040 {"DeprecationWarning", &PyExc_DeprecationWarning
, &PyExc_Warning
,
1041 DeprecationWarning__doc__
},
1042 {"SyntaxWarning", &PyExc_SyntaxWarning
, &PyExc_Warning
, SyntaxWarning__doc__
},
1043 {"RuntimeWarning", &PyExc_RuntimeWarning
, &PyExc_Warning
,
1044 RuntimeWarning__doc__
},
1052 init_exceptions(void)
1054 char *modulename
= "exceptions";
1055 int modnamesz
= strlen(modulename
);
1058 PyObject
*me
= Py_InitModule(modulename
, functions
);
1059 PyObject
*mydict
= PyModule_GetDict(me
);
1060 PyObject
*bltinmod
= PyImport_ImportModule("__builtin__");
1061 PyObject
*bdict
= PyModule_GetDict(bltinmod
);
1062 PyObject
*doc
= PyString_FromString(module__doc__
);
1065 PyDict_SetItemString(mydict
, "__doc__", doc
);
1067 if (PyErr_Occurred())
1068 Py_FatalError("exceptions bootstrapping error.");
1070 /* This is the base class of all exceptions, so make it first. */
1071 if (make_Exception(modulename
) ||
1072 PyDict_SetItemString(mydict
, "Exception", PyExc_Exception
) ||
1073 PyDict_SetItemString(bdict
, "Exception", PyExc_Exception
))
1075 Py_FatalError("Base class `Exception' could not be created.");
1078 /* Now we can programmatically create all the remaining exceptions.
1079 * Remember to start the loop at 1 to skip Exceptions.
1081 for (i
=1; exctable
[i
].name
; i
++) {
1083 char *cname
= PyMem_NEW(char, modnamesz
+strlen(exctable
[i
].name
)+2);
1086 (void)strcpy(cname
, modulename
);
1087 (void)strcat(cname
, ".");
1088 (void)strcat(cname
, exctable
[i
].name
);
1090 if (exctable
[i
].base
== 0)
1091 base
= PyExc_StandardError
;
1093 base
= *exctable
[i
].base
;
1095 status
= make_class(exctable
[i
].exc
, base
, cname
,
1096 exctable
[i
].methods
,
1097 exctable
[i
].docstr
);
1102 Py_FatalError("Standard exception classes could not be created.");
1104 if (exctable
[i
].classinit
) {
1105 status
= (*exctable
[i
].classinit
)(*exctable
[i
].exc
);
1107 Py_FatalError("An exception class could not be initialized.");
1110 /* Now insert the class into both this module and the __builtin__
1113 if (PyDict_SetItemString(mydict
, exctable
[i
].name
, *exctable
[i
].exc
) ||
1114 PyDict_SetItemString(bdict
, exctable
[i
].name
, *exctable
[i
].exc
))
1116 Py_FatalError("Module dictionary insertion problem.");
1120 /* Now we need to pre-allocate a MemoryError instance */
1121 args
= Py_BuildValue("()");
1123 !(PyExc_MemoryErrorInst
= PyEval_CallObject(PyExc_MemoryError
, args
)))
1125 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
1129 /* We're done with __builtin__ */
1130 Py_DECREF(bltinmod
);
1135 fini_exceptions(void)
1139 Py_XDECREF(PyExc_MemoryErrorInst
);
1140 PyExc_MemoryErrorInst
= NULL
;
1142 for (i
=0; exctable
[i
].name
; i
++) {
1143 /* clear the class's dictionary, freeing up circular references
1144 * between the class and its methods.
1146 PyObject
* cdict
= PyObject_GetAttrString(*exctable
[i
].exc
, "__dict__");
1147 PyDict_Clear(cdict
);
1150 /* Now decref the exception class */
1151 Py_XDECREF(*exctable
[i
].exc
);
1152 *exctable
[i
].exc
= NULL
;