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.
29 /* NOTE: If the exception class hierarchy changes, don't forget to update
30 * Doc/lib/libexcs.tex!
33 PyDoc_STRVAR(module__doc__
,
34 "Python's standard exception class hierarchy.\n\
36 Before Python 1.5, the standard exceptions were all simple string objects.\n\
37 In Python 1.5, the standard exceptions were converted to classes organized\n\
38 into a relatively flat hierarchy. String-based standard exceptions were\n\
39 optional, or used as a fallback if some problem occurred while importing\n\
40 the exception module. With Python 1.6, optional string-based standard\n\
41 exceptions were removed (along with the -X command line flag).\n\
43 The class exceptions were implemented in such a way as to be almost\n\
44 completely backward compatible. Some tricky uses of IOError could\n\
45 potentially have broken, but by Python 1.6, all of these should have\n\
46 been fixed. As of Python 1.6, the class-based standard exceptions are\n\
47 now implemented in C, and are guaranteed to exist in the Python\n\
50 Here is a rundown of the class hierarchy. The classes found here are\n\
51 inserted into both the exceptions module and the `built-in' module. It is\n\
52 recommended that user defined class based exceptions be derived from the\n\
53 `Exception' class, although this is currently not enforced.\n"
54 /* keep string pieces "small" */
62 | +-- KeyboardInterrupt\n\
64 | +-- EnvironmentError\n\
69 | | +-- WindowsError\n\
75 | | +-- NotImplementedError\n\
79 | | +-- UnboundLocalError\n\
81 | +-- AttributeError\n\
84 | | +-- IndentationError\n\
89 | +-- AssertionError\n\
95 | +-- ArithmeticError\n\
97 | | +-- OverflowError\n\
98 | | +-- ZeroDivisionError\n\
99 | | +-- FloatingPointError\n\
103 | | +-- UnicodeError\n\
105 | | +-- UnicodeEncodeError\n\
106 | | +-- UnicodeDecodeError\n\
107 | | +-- UnicodeTranslateError\n\
109 | +-- ReferenceError\n\
116 +-- DeprecationWarning\n\
117 +-- PendingDeprecationWarning\n\
119 +-- OverflowWarning\n\
120 +-- RuntimeWarning\n\
125 /* Helper function for populating a dictionary with method wrappers. */
127 populate_methods(PyObject
*klass
, PyObject
*dict
, PyMethodDef
*methods
)
135 module
= PyString_FromString("exceptions");
138 while (methods
->ml_name
) {
139 /* get a wrapper for the built-in function */
140 PyObject
*func
= PyCFunction_NewEx(methods
, NULL
, module
);
146 /* turn the function into an unbound method */
147 if (!(meth
= PyMethod_New(func
, NULL
, klass
))) {
152 /* add method to dictionary */
153 status
= PyDict_SetItemString(dict
, methods
->ml_name
, meth
);
157 /* stop now if an error occurred, otherwise do the next method */
171 /* This function is used to create all subsequent exception classes. */
173 make_class(PyObject
**klass
, PyObject
*base
,
174 char *name
, PyMethodDef
*methods
,
177 PyObject
*dict
= PyDict_New();
178 PyObject
*str
= NULL
;
184 /* If an error occurs from here on, goto finally instead of explicitly
189 if (!(str
= PyString_FromString(docstr
)))
191 if (PyDict_SetItemString(dict
, "__doc__", str
))
195 if (!(*klass
= PyErr_NewException(name
, base
, dict
)))
198 if (populate_methods(*klass
, dict
, methods
)) {
213 /* Use this for *args signatures, otherwise just use PyArg_ParseTuple() */
215 get_self(PyObject
*args
)
217 PyObject
*self
= PyTuple_GetItem(args
, 0);
219 /* Watch out for being called to early in the bootstrapping process */
220 if (PyExc_TypeError
) {
221 PyErr_SetString(PyExc_TypeError
,
222 "unbound method must be called with instance as first argument");
231 /* Notes on bootstrapping the exception classes.
233 * First thing we create is the base class for all exceptions, called
234 * appropriately enough: Exception. Creation of this class makes no
235 * assumptions about the existence of any other exception class -- except
236 * for TypeError, which can conditionally exist.
238 * Next, StandardError is created (which is quite simple) followed by
239 * TypeError, because the instantiation of other exceptions can potentially
240 * throw a TypeError. Once these exceptions are created, all the others
241 * can be created in any order. See the static exctable below for the
242 * explicit bootstrap order.
244 * All classes after Exception can be created using PyErr_NewException().
247 PyDoc_STRVAR(Exception__doc__
, "Common base class for all exceptions.");
251 Exception__init__(PyObject
*self
, PyObject
*args
)
255 if (!(self
= get_self(args
)))
258 /* set args attribute */
259 /* XXX size is only a hint */
260 args
= PySequence_GetSlice(args
, 1, PySequence_Size(args
));
263 status
= PyObject_SetAttrString(self
, "args", args
);
274 Exception__str__(PyObject
*self
, PyObject
*args
)
278 if (!PyArg_ParseTuple(args
, "O:__str__", &self
))
281 args
= PyObject_GetAttrString(self
, "args");
285 switch (PySequence_Size(args
)) {
287 out
= PyString_FromString("");
291 PyObject
*tmp
= PySequence_GetItem(args
, 0);
293 out
= PyObject_Str(tmp
);
304 out
= PyObject_Str(args
);
314 Exception__getitem__(PyObject
*self
, PyObject
*args
)
319 if (!PyArg_ParseTuple(args
, "OO:__getitem__", &self
, &index
))
322 args
= PyObject_GetAttrString(self
, "args");
326 out
= PyObject_GetItem(args
, index
);
333 Exception_methods
[] = {
334 /* methods for the Exception class */
335 { "__getitem__", Exception__getitem__
, METH_VARARGS
},
336 { "__str__", Exception__str__
, METH_VARARGS
},
337 { "__init__", Exception__init__
, METH_VARARGS
},
343 make_Exception(char *modulename
)
345 PyObject
*dict
= PyDict_New();
346 PyObject
*str
= NULL
;
347 PyObject
*name
= NULL
;
353 /* If an error occurs from here on, goto finally instead of explicitly
357 if (!(str
= PyString_FromString(modulename
)))
359 if (PyDict_SetItemString(dict
, "__module__", str
))
362 if (!(str
= PyString_FromString(Exception__doc__
)))
364 if (PyDict_SetItemString(dict
, "__doc__", str
))
367 if (!(name
= PyString_FromString("Exception")))
370 if (!(PyExc_Exception
= PyClass_New(NULL
, dict
, name
)))
373 /* Now populate the dictionary with the method suite */
374 if (populate_methods(PyExc_Exception
, dict
, Exception_methods
))
375 /* Don't need to reclaim PyExc_Exception here because that'll
376 * happen during interpreter shutdown.
391 PyDoc_STRVAR(StandardError__doc__
,
392 "Base class for all standard Python exceptions.");
394 PyDoc_STRVAR(TypeError__doc__
, "Inappropriate argument type.");
396 PyDoc_STRVAR(StopIteration__doc__
, "Signal the end from iterator.next().");
400 PyDoc_STRVAR(SystemExit__doc__
, "Request to exit from the interpreter.");
404 SystemExit__init__(PyObject
*self
, PyObject
*args
)
409 if (!(self
= get_self(args
)))
412 /* Set args attribute. */
413 if (!(args
= PySequence_GetSlice(args
, 1, PySequence_Size(args
))))
416 status
= PyObject_SetAttrString(self
, "args", args
);
422 /* set code attribute */
423 switch (PySequence_Size(args
)) {
429 code
= PySequence_GetItem(args
, 0);
440 status
= PyObject_SetAttrString(self
, "code", code
);
451 static PyMethodDef SystemExit_methods
[] = {
452 { "__init__", SystemExit__init__
, METH_VARARGS
},
458 PyDoc_STRVAR(KeyboardInterrupt__doc__
, "Program interrupted by user.");
460 PyDoc_STRVAR(ImportError__doc__
,
461 "Import can't find module, or can't find name in module.");
465 PyDoc_STRVAR(EnvironmentError__doc__
, "Base class for I/O related errors.");
469 EnvironmentError__init__(PyObject
*self
, PyObject
*args
)
471 PyObject
*item0
= NULL
;
472 PyObject
*item1
= NULL
;
473 PyObject
*item2
= NULL
;
474 PyObject
*subslice
= NULL
;
475 PyObject
*rtnval
= NULL
;
477 if (!(self
= get_self(args
)))
480 if (!(args
= PySequence_GetSlice(args
, 1, PySequence_Size(args
))))
483 if (PyObject_SetAttrString(self
, "args", args
) ||
484 PyObject_SetAttrString(self
, "errno", Py_None
) ||
485 PyObject_SetAttrString(self
, "strerror", Py_None
) ||
486 PyObject_SetAttrString(self
, "filename", Py_None
))
491 switch (PySequence_Size(args
)) {
493 /* Where a function has a single filename, such as open() or some
494 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
495 * called, giving a third argument which is the filename. But, so
496 * that old code using in-place unpacking doesn't break, e.g.:
498 * except IOError, (errno, strerror):
500 * we hack args so that it only contains two items. This also
501 * means we need our own __str__() which prints out the filename
502 * when it was supplied.
504 item0
= PySequence_GetItem(args
, 0);
505 item1
= PySequence_GetItem(args
, 1);
506 item2
= PySequence_GetItem(args
, 2);
507 if (!item0
|| !item1
|| !item2
)
510 if (PyObject_SetAttrString(self
, "errno", item0
) ||
511 PyObject_SetAttrString(self
, "strerror", item1
) ||
512 PyObject_SetAttrString(self
, "filename", item2
))
517 subslice
= PySequence_GetSlice(args
, 0, 2);
518 if (!subslice
|| PyObject_SetAttrString(self
, "args", subslice
))
523 /* Used when PyErr_SetFromErrno() is called and no filename
526 item0
= PySequence_GetItem(args
, 0);
527 item1
= PySequence_GetItem(args
, 1);
528 if (!item0
|| !item1
)
531 if (PyObject_SetAttrString(self
, "errno", item0
) ||
532 PyObject_SetAttrString(self
, "strerror", item1
))
551 Py_XDECREF(subslice
);
557 EnvironmentError__str__(PyObject
*self
, PyObject
*args
)
559 PyObject
*originalself
= self
;
563 PyObject
*rtnval
= NULL
;
565 if (!PyArg_ParseTuple(args
, "O:__str__", &self
))
568 filename
= PyObject_GetAttrString(self
, "filename");
569 serrno
= PyObject_GetAttrString(self
, "errno");
570 strerror
= PyObject_GetAttrString(self
, "strerror");
571 if (!filename
|| !serrno
|| !strerror
)
574 if (filename
!= Py_None
) {
575 PyObject
*fmt
= PyString_FromString("[Errno %s] %s: %s");
576 PyObject
*repr
= PyObject_Repr(filename
);
577 PyObject
*tuple
= PyTuple_New(3);
579 if (!fmt
|| !repr
|| !tuple
) {
586 PyTuple_SET_ITEM(tuple
, 0, serrno
);
587 PyTuple_SET_ITEM(tuple
, 1, strerror
);
588 PyTuple_SET_ITEM(tuple
, 2, repr
);
590 rtnval
= PyString_Format(fmt
, tuple
);
594 /* already freed because tuple owned only reference */
598 else if (PyObject_IsTrue(serrno
) && PyObject_IsTrue(strerror
)) {
599 PyObject
*fmt
= PyString_FromString("[Errno %s] %s");
600 PyObject
*tuple
= PyTuple_New(2);
602 if (!fmt
|| !tuple
) {
608 PyTuple_SET_ITEM(tuple
, 0, serrno
);
609 PyTuple_SET_ITEM(tuple
, 1, strerror
);
611 rtnval
= PyString_Format(fmt
, tuple
);
615 /* already freed because tuple owned only reference */
620 /* The original Python code said:
622 * return StandardError.__str__(self)
624 * but there is no StandardError__str__() function; we happen to
625 * know that's just a pass through to Exception__str__().
627 rtnval
= Exception__str__(originalself
, args
);
630 Py_XDECREF(filename
);
632 Py_XDECREF(strerror
);
638 PyMethodDef EnvironmentError_methods
[] = {
639 {"__init__", EnvironmentError__init__
, METH_VARARGS
},
640 {"__str__", EnvironmentError__str__
, METH_VARARGS
},
647 PyDoc_STRVAR(IOError__doc__
, "I/O operation failed.");
649 PyDoc_STRVAR(OSError__doc__
, "OS system call failed.");
652 PyDoc_STRVAR(WindowsError__doc__
, "MS-Windows OS system call failed.");
653 #endif /* MS_WINDOWS */
657 VMSError__doc__
[] = "OpenVMS OS system call failed.";
660 PyDoc_STRVAR(EOFError__doc__
, "Read beyond end of file.");
662 PyDoc_STRVAR(RuntimeError__doc__
, "Unspecified run-time error.");
664 PyDoc_STRVAR(NotImplementedError__doc__
,
665 "Method or function hasn't been implemented yet.");
667 PyDoc_STRVAR(NameError__doc__
, "Name not found globally.");
669 PyDoc_STRVAR(UnboundLocalError__doc__
,
670 "Local name referenced but not bound to a value.");
672 PyDoc_STRVAR(AttributeError__doc__
, "Attribute not found.");
676 PyDoc_STRVAR(SyntaxError__doc__
, "Invalid syntax.");
680 SyntaxError__classinit__(PyObject
*klass
)
683 PyObject
*emptystring
= PyString_FromString("");
685 /* Additional class-creation time initializations */
687 PyObject_SetAttrString(klass
, "msg", emptystring
) ||
688 PyObject_SetAttrString(klass
, "filename", Py_None
) ||
689 PyObject_SetAttrString(klass
, "lineno", Py_None
) ||
690 PyObject_SetAttrString(klass
, "offset", Py_None
) ||
691 PyObject_SetAttrString(klass
, "text", Py_None
) ||
692 PyObject_SetAttrString(klass
, "print_file_and_line", Py_None
))
696 Py_XDECREF(emptystring
);
702 SyntaxError__init__(PyObject
*self
, PyObject
*args
)
704 PyObject
*rtnval
= NULL
;
707 if (!(self
= get_self(args
)))
710 if (!(args
= PySequence_GetSlice(args
, 1, PySequence_Size(args
))))
713 if (PyObject_SetAttrString(self
, "args", args
))
716 lenargs
= PySequence_Size(args
);
718 PyObject
*item0
= PySequence_GetItem(args
, 0);
723 status
= PyObject_SetAttrString(self
, "msg", item0
);
729 PyObject
*info
= PySequence_GetItem(args
, 1);
730 PyObject
*filename
= NULL
, *lineno
= NULL
;
731 PyObject
*offset
= NULL
, *text
= NULL
;
737 filename
= PySequence_GetItem(info
, 0);
738 if (filename
!= NULL
) {
739 lineno
= PySequence_GetItem(info
, 1);
740 if (lineno
!= NULL
) {
741 offset
= PySequence_GetItem(info
, 2);
742 if (offset
!= NULL
) {
743 text
= PySequence_GetItem(info
, 3);
746 PyObject_SetAttrString(self
, "filename", filename
)
747 || PyObject_SetAttrString(self
, "lineno", lineno
)
748 || PyObject_SetAttrString(self
, "offset", offset
)
749 || PyObject_SetAttrString(self
, "text", text
);
772 /* This is called "my_basename" instead of just "basename" to avoid name
773 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
774 defined, and Python does define that. */
776 my_basename(char *name
)
783 while (*cp
!= '\0') {
793 SyntaxError__str__(PyObject
*self
, PyObject
*args
)
797 PyObject
*filename
, *lineno
, *result
;
799 if (!PyArg_ParseTuple(args
, "O:__str__", &self
))
802 if (!(msg
= PyObject_GetAttrString(self
, "msg")))
805 str
= PyObject_Str(msg
);
809 /* XXX -- do all the additional formatting with filename and
812 if (str
!= NULL
&& PyString_Check(str
)) {
813 int have_filename
= 0;
817 if ((filename
= PyObject_GetAttrString(self
, "filename")) != NULL
)
818 have_filename
= PyString_Check(filename
);
822 if ((lineno
= PyObject_GetAttrString(self
, "lineno")) != NULL
)
823 have_lineno
= PyInt_Check(lineno
);
827 if (have_filename
|| have_lineno
) {
828 int bufsize
= PyString_GET_SIZE(str
) + 64;
830 bufsize
+= PyString_GET_SIZE(filename
);
832 buffer
= PyMem_MALLOC(bufsize
);
833 if (buffer
!= NULL
) {
834 if (have_filename
&& have_lineno
)
835 PyOS_snprintf(buffer
, bufsize
, "%s (%s, line %ld)",
836 PyString_AS_STRING(str
),
837 my_basename(PyString_AS_STRING(filename
)),
838 PyInt_AsLong(lineno
));
839 else if (have_filename
)
840 PyOS_snprintf(buffer
, bufsize
, "%s (%s)",
841 PyString_AS_STRING(str
),
842 my_basename(PyString_AS_STRING(filename
)));
843 else if (have_lineno
)
844 PyOS_snprintf(buffer
, bufsize
, "%s (line %ld)",
845 PyString_AS_STRING(str
),
846 PyInt_AsLong(lineno
));
848 result
= PyString_FromString(buffer
);
857 Py_XDECREF(filename
);
864 static PyMethodDef SyntaxError_methods
[] = {
865 {"__init__", SyntaxError__init__
, METH_VARARGS
},
866 {"__str__", SyntaxError__str__
, METH_VARARGS
},
872 KeyError__str__(PyObject
*self
, PyObject
*args
)
877 if (!PyArg_ParseTuple(args
, "O:__str__", &self
))
880 if (!(argsattr
= PyObject_GetAttrString(self
, "args")))
883 /* If args is a tuple of exactly one item, apply repr to args[0].
884 This is done so that e.g. the exception raised by {}[''] prints
886 rather than the confusing
888 alone. The downside is that if KeyError is raised with an explanatory
889 string, that string will be displayed in quotes. Too bad.
890 If args is anything else, use the default Exception__str__().
892 if (PyTuple_Check(argsattr
) && PyTuple_GET_SIZE(argsattr
) == 1) {
893 PyObject
*key
= PyTuple_GET_ITEM(argsattr
, 0);
894 result
= PyObject_Repr(key
);
897 result
= Exception__str__(self
, args
);
903 static PyMethodDef KeyError_methods
[] = {
904 {"__str__", KeyError__str__
, METH_VARARGS
},
909 #ifdef Py_USING_UNICODE
911 int get_int(PyObject
*exc
, const char *name
, int *value
)
913 PyObject
*attr
= PyObject_GetAttrString(exc
, (char *)name
);
917 if (!PyInt_Check(attr
)) {
918 PyErr_Format(PyExc_TypeError
, "%.200s attribute must be int", name
);
922 *value
= PyInt_AS_LONG(attr
);
929 int set_int(PyObject
*exc
, const char *name
, int value
)
931 PyObject
*obj
= PyInt_FromLong(value
);
936 result
= PyObject_SetAttrString(exc
, (char *)name
, obj
);
943 PyObject
*get_string(PyObject
*exc
, const char *name
)
945 PyObject
*attr
= PyObject_GetAttrString(exc
, (char *)name
);
949 if (!PyString_Check(attr
)) {
950 PyErr_Format(PyExc_TypeError
, "%.200s attribute must be str", name
);
959 int set_string(PyObject
*exc
, const char *name
, const char *value
)
961 PyObject
*obj
= PyString_FromString(value
);
966 result
= PyObject_SetAttrString(exc
, (char *)name
, obj
);
973 PyObject
*get_unicode(PyObject
*exc
, const char *name
)
975 PyObject
*attr
= PyObject_GetAttrString(exc
, (char *)name
);
979 if (!PyUnicode_Check(attr
)) {
980 PyErr_Format(PyExc_TypeError
, "%.200s attribute must be unicode", name
);
987 PyObject
* PyUnicodeEncodeError_GetEncoding(PyObject
*exc
)
989 return get_string(exc
, "encoding");
992 PyObject
* PyUnicodeDecodeError_GetEncoding(PyObject
*exc
)
994 return get_string(exc
, "encoding");
997 PyObject
*PyUnicodeEncodeError_GetObject(PyObject
*exc
)
999 return get_unicode(exc
, "object");
1002 PyObject
*PyUnicodeDecodeError_GetObject(PyObject
*exc
)
1004 return get_string(exc
, "object");
1007 PyObject
*PyUnicodeTranslateError_GetObject(PyObject
*exc
)
1009 return get_unicode(exc
, "object");
1012 int PyUnicodeEncodeError_GetStart(PyObject
*exc
, int *start
)
1014 if (!get_int(exc
, "start", start
)) {
1015 PyObject
*object
= PyUnicodeEncodeError_GetObject(exc
);
1019 size
= PyUnicode_GET_SIZE(object
);
1031 int PyUnicodeDecodeError_GetStart(PyObject
*exc
, int *start
)
1033 if (!get_int(exc
, "start", start
)) {
1034 PyObject
*object
= PyUnicodeDecodeError_GetObject(exc
);
1038 size
= PyString_GET_SIZE(object
);
1050 int PyUnicodeTranslateError_GetStart(PyObject
*exc
, int *start
)
1052 return PyUnicodeEncodeError_GetStart(exc
, start
);
1056 int PyUnicodeEncodeError_SetStart(PyObject
*exc
, int start
)
1058 return set_int(exc
, "start", start
);
1062 int PyUnicodeDecodeError_SetStart(PyObject
*exc
, int start
)
1064 return set_int(exc
, "start", start
);
1068 int PyUnicodeTranslateError_SetStart(PyObject
*exc
, int start
)
1070 return set_int(exc
, "start", start
);
1074 int PyUnicodeEncodeError_GetEnd(PyObject
*exc
, int *end
)
1076 if (!get_int(exc
, "end", end
)) {
1077 PyObject
*object
= PyUnicodeEncodeError_GetObject(exc
);
1081 size
= PyUnicode_GET_SIZE(object
);
1093 int PyUnicodeDecodeError_GetEnd(PyObject
*exc
, int *end
)
1095 if (!get_int(exc
, "end", end
)) {
1096 PyObject
*object
= PyUnicodeDecodeError_GetObject(exc
);
1100 size
= PyString_GET_SIZE(object
);
1112 int PyUnicodeTranslateError_GetEnd(PyObject
*exc
, int *start
)
1114 return PyUnicodeEncodeError_GetEnd(exc
, start
);
1118 int PyUnicodeEncodeError_SetEnd(PyObject
*exc
, int end
)
1120 return set_int(exc
, "end", end
);
1124 int PyUnicodeDecodeError_SetEnd(PyObject
*exc
, int end
)
1126 return set_int(exc
, "end", end
);
1130 int PyUnicodeTranslateError_SetEnd(PyObject
*exc
, int end
)
1132 return set_int(exc
, "end", end
);
1136 PyObject
*PyUnicodeEncodeError_GetReason(PyObject
*exc
)
1138 return get_string(exc
, "reason");
1142 PyObject
*PyUnicodeDecodeError_GetReason(PyObject
*exc
)
1144 return get_string(exc
, "reason");
1148 PyObject
*PyUnicodeTranslateError_GetReason(PyObject
*exc
)
1150 return get_string(exc
, "reason");
1154 int PyUnicodeEncodeError_SetReason(PyObject
*exc
, const char *reason
)
1156 return set_string(exc
, "reason", reason
);
1160 int PyUnicodeDecodeError_SetReason(PyObject
*exc
, const char *reason
)
1162 return set_string(exc
, "reason", reason
);
1166 int PyUnicodeTranslateError_SetReason(PyObject
*exc
, const char *reason
)
1168 return set_string(exc
, "reason", reason
);
1173 UnicodeError__init__(PyObject
*self
, PyObject
*args
, PyTypeObject
*objecttype
)
1175 PyObject
*rtnval
= NULL
;
1182 if (!(self
= get_self(args
)))
1185 if (!(args
= PySequence_GetSlice(args
, 1, PySequence_Size(args
))))
1188 if (!PyArg_ParseTuple(args
, "O!O!O!O!O!",
1189 &PyString_Type
, &encoding
,
1190 objecttype
, &object
,
1191 &PyInt_Type
, &start
,
1193 &PyString_Type
, &reason
))
1196 if (PyObject_SetAttrString(self
, "args", args
))
1199 if (PyObject_SetAttrString(self
, "encoding", encoding
))
1201 if (PyObject_SetAttrString(self
, "object", object
))
1203 if (PyObject_SetAttrString(self
, "start", start
))
1205 if (PyObject_SetAttrString(self
, "end", end
))
1207 if (PyObject_SetAttrString(self
, "reason", reason
))
1220 UnicodeEncodeError__init__(PyObject
*self
, PyObject
*args
)
1222 return UnicodeError__init__(self
, args
, &PyUnicode_Type
);
1226 UnicodeEncodeError__str__(PyObject
*self
, PyObject
*arg
)
1228 PyObject
*encodingObj
= NULL
;
1229 PyObject
*objectObj
= NULL
;
1232 PyObject
*reasonObj
= NULL
;
1234 PyObject
*result
= NULL
;
1238 if (!(encodingObj
= PyUnicodeEncodeError_GetEncoding(self
)))
1241 if (!(objectObj
= PyUnicodeEncodeError_GetObject(self
)))
1244 if (PyUnicodeEncodeError_GetStart(self
, &start
))
1247 if (PyUnicodeEncodeError_GetEnd(self
, &end
))
1250 if (!(reasonObj
= PyUnicodeEncodeError_GetReason(self
)))
1254 PyOS_snprintf(buffer
, sizeof(buffer
),
1255 "'%.400s' codec can't encode character '\\u%x' in position %d: %.400s",
1256 PyString_AS_STRING(encodingObj
),
1257 (int)PyUnicode_AS_UNICODE(objectObj
)[start
],
1259 PyString_AS_STRING(reasonObj
)
1263 PyOS_snprintf(buffer
, sizeof(buffer
),
1264 "'%.400s' codec can't encode characters in position %d-%d: %.400s",
1265 PyString_AS_STRING(encodingObj
),
1268 PyString_AS_STRING(reasonObj
)
1271 result
= PyString_FromString(buffer
);
1274 Py_XDECREF(reasonObj
);
1275 Py_XDECREF(objectObj
);
1276 Py_XDECREF(encodingObj
);
1280 static PyMethodDef UnicodeEncodeError_methods
[] = {
1281 {"__init__", UnicodeEncodeError__init__
, METH_VARARGS
},
1282 {"__str__", UnicodeEncodeError__str__
, METH_O
},
1287 PyObject
* PyUnicodeEncodeError_Create(
1288 const char *encoding
, const Py_UNICODE
*object
, int length
,
1289 int start
, int end
, const char *reason
)
1291 return PyObject_CallFunction(PyExc_UnicodeEncodeError
, "su#iis",
1292 encoding
, object
, length
, start
, end
, reason
);
1297 UnicodeDecodeError__init__(PyObject
*self
, PyObject
*args
)
1299 return UnicodeError__init__(self
, args
, &PyString_Type
);
1303 UnicodeDecodeError__str__(PyObject
*self
, PyObject
*arg
)
1305 PyObject
*encodingObj
= NULL
;
1306 PyObject
*objectObj
= NULL
;
1309 PyObject
*reasonObj
= NULL
;
1311 PyObject
*result
= NULL
;
1315 if (!(encodingObj
= PyUnicodeDecodeError_GetEncoding(self
)))
1318 if (!(objectObj
= PyUnicodeDecodeError_GetObject(self
)))
1321 if (PyUnicodeDecodeError_GetStart(self
, &start
))
1324 if (PyUnicodeDecodeError_GetEnd(self
, &end
))
1327 if (!(reasonObj
= PyUnicodeDecodeError_GetReason(self
)))
1331 PyOS_snprintf(buffer
, sizeof(buffer
),
1332 "'%.400s' codec can't decode byte 0x%x in position %d: %.400s",
1333 PyString_AS_STRING(encodingObj
),
1334 ((int)PyString_AS_STRING(objectObj
)[start
])&0xff,
1336 PyString_AS_STRING(reasonObj
)
1340 PyOS_snprintf(buffer
, sizeof(buffer
),
1341 "'%.400s' codec can't decode bytes in position %d-%d: %.400s",
1342 PyString_AS_STRING(encodingObj
),
1345 PyString_AS_STRING(reasonObj
)
1348 result
= PyString_FromString(buffer
);
1351 Py_XDECREF(reasonObj
);
1352 Py_XDECREF(objectObj
);
1353 Py_XDECREF(encodingObj
);
1357 static PyMethodDef UnicodeDecodeError_methods
[] = {
1358 {"__init__", UnicodeDecodeError__init__
, METH_VARARGS
},
1359 {"__str__", UnicodeDecodeError__str__
, METH_O
},
1364 PyObject
* PyUnicodeDecodeError_Create(
1365 const char *encoding
, const char *object
, int length
,
1366 int start
, int end
, const char *reason
)
1368 return PyObject_CallFunction(PyExc_UnicodeDecodeError
, "ss#iis",
1369 encoding
, object
, length
, start
, end
, reason
);
1374 UnicodeTranslateError__init__(PyObject
*self
, PyObject
*args
)
1376 PyObject
*rtnval
= NULL
;
1382 if (!(self
= get_self(args
)))
1385 if (!(args
= PySequence_GetSlice(args
, 1, PySequence_Size(args
))))
1388 if (!PyArg_ParseTuple(args
, "O!O!O!O!",
1389 &PyUnicode_Type
, &object
,
1390 &PyInt_Type
, &start
,
1392 &PyString_Type
, &reason
))
1395 if (PyObject_SetAttrString(self
, "args", args
))
1398 if (PyObject_SetAttrString(self
, "object", object
))
1400 if (PyObject_SetAttrString(self
, "start", start
))
1402 if (PyObject_SetAttrString(self
, "end", end
))
1404 if (PyObject_SetAttrString(self
, "reason", reason
))
1417 UnicodeTranslateError__str__(PyObject
*self
, PyObject
*arg
)
1419 PyObject
*objectObj
= NULL
;
1422 PyObject
*reasonObj
= NULL
;
1424 PyObject
*result
= NULL
;
1428 if (!(objectObj
= PyUnicodeTranslateError_GetObject(self
)))
1431 if (PyUnicodeTranslateError_GetStart(self
, &start
))
1434 if (PyUnicodeTranslateError_GetEnd(self
, &end
))
1437 if (!(reasonObj
= PyUnicodeTranslateError_GetReason(self
)))
1441 PyOS_snprintf(buffer
, sizeof(buffer
),
1442 "can't translate character '\\u%x' in position %d: %.400s",
1443 (int)PyUnicode_AS_UNICODE(objectObj
)[start
],
1445 PyString_AS_STRING(reasonObj
)
1449 PyOS_snprintf(buffer
, sizeof(buffer
),
1450 "can't translate characters in position %d-%d: %.400s",
1453 PyString_AS_STRING(reasonObj
)
1456 result
= PyString_FromString(buffer
);
1459 Py_XDECREF(reasonObj
);
1460 Py_XDECREF(objectObj
);
1464 static PyMethodDef UnicodeTranslateError_methods
[] = {
1465 {"__init__", UnicodeTranslateError__init__
, METH_VARARGS
},
1466 {"__str__", UnicodeTranslateError__str__
, METH_O
},
1471 PyObject
* PyUnicodeTranslateError_Create(
1472 const Py_UNICODE
*object
, int length
,
1473 int start
, int end
, const char *reason
)
1475 return PyObject_CallFunction(PyExc_UnicodeTranslateError
, "u#iis",
1476 object
, length
, start
, end
, reason
);
1482 /* Exception doc strings */
1484 PyDoc_STRVAR(AssertionError__doc__
, "Assertion failed.");
1486 PyDoc_STRVAR(LookupError__doc__
, "Base class for lookup errors.");
1488 PyDoc_STRVAR(IndexError__doc__
, "Sequence index out of range.");
1490 PyDoc_STRVAR(KeyError__doc__
, "Mapping key not found.");
1492 PyDoc_STRVAR(ArithmeticError__doc__
, "Base class for arithmetic errors.");
1494 PyDoc_STRVAR(OverflowError__doc__
, "Result too large to be represented.");
1496 PyDoc_STRVAR(ZeroDivisionError__doc__
,
1497 "Second argument to a division or modulo operation was zero.");
1499 PyDoc_STRVAR(FloatingPointError__doc__
, "Floating point operation failed.");
1501 PyDoc_STRVAR(ValueError__doc__
,
1502 "Inappropriate argument value (of correct type).");
1504 PyDoc_STRVAR(UnicodeError__doc__
, "Unicode related error.");
1506 #ifdef Py_USING_UNICODE
1507 PyDoc_STRVAR(UnicodeEncodeError__doc__
, "Unicode encoding error.");
1509 PyDoc_STRVAR(UnicodeDecodeError__doc__
, "Unicode decoding error.");
1511 PyDoc_STRVAR(UnicodeTranslateError__doc__
, "Unicode translation error.");
1514 PyDoc_STRVAR(SystemError__doc__
,
1515 "Internal error in the Python interpreter.\n\
1517 Please report this to the Python maintainer, along with the traceback,\n\
1518 the Python version, and the hardware/OS platform and version.");
1520 PyDoc_STRVAR(ReferenceError__doc__
,
1521 "Weak ref proxy used after referent went away.");
1523 PyDoc_STRVAR(MemoryError__doc__
, "Out of memory.");
1525 PyDoc_STRVAR(IndentationError__doc__
, "Improper indentation.");
1527 PyDoc_STRVAR(TabError__doc__
, "Improper mixture of spaces and tabs.");
1529 /* Warning category docstrings */
1531 PyDoc_STRVAR(Warning__doc__
, "Base class for warning categories.");
1533 PyDoc_STRVAR(UserWarning__doc__
,
1534 "Base class for warnings generated by user code.");
1536 PyDoc_STRVAR(DeprecationWarning__doc__
,
1537 "Base class for warnings about deprecated features.");
1539 PyDoc_STRVAR(PendingDeprecationWarning__doc__
,
1540 "Base class for warnings about features which will be deprecated "
1543 PyDoc_STRVAR(SyntaxWarning__doc__
,
1544 "Base class for warnings about dubious syntax.");
1546 PyDoc_STRVAR(OverflowWarning__doc__
,
1547 "Base class for warnings about numeric overflow.");
1549 PyDoc_STRVAR(RuntimeWarning__doc__
,
1550 "Base class for warnings about dubious runtime behavior.");
1552 PyDoc_STRVAR(FutureWarning__doc__
,
1553 "Base class for warnings about constructs that will change semantically "
1558 /* module global functions */
1559 static PyMethodDef functions
[] = {
1566 /* Global C API defined exceptions */
1568 PyObject
*PyExc_Exception
;
1569 PyObject
*PyExc_StopIteration
;
1570 PyObject
*PyExc_StandardError
;
1571 PyObject
*PyExc_ArithmeticError
;
1572 PyObject
*PyExc_LookupError
;
1574 PyObject
*PyExc_AssertionError
;
1575 PyObject
*PyExc_AttributeError
;
1576 PyObject
*PyExc_EOFError
;
1577 PyObject
*PyExc_FloatingPointError
;
1578 PyObject
*PyExc_EnvironmentError
;
1579 PyObject
*PyExc_IOError
;
1580 PyObject
*PyExc_OSError
;
1581 PyObject
*PyExc_ImportError
;
1582 PyObject
*PyExc_IndexError
;
1583 PyObject
*PyExc_KeyError
;
1584 PyObject
*PyExc_KeyboardInterrupt
;
1585 PyObject
*PyExc_MemoryError
;
1586 PyObject
*PyExc_NameError
;
1587 PyObject
*PyExc_OverflowError
;
1588 PyObject
*PyExc_RuntimeError
;
1589 PyObject
*PyExc_NotImplementedError
;
1590 PyObject
*PyExc_SyntaxError
;
1591 PyObject
*PyExc_IndentationError
;
1592 PyObject
*PyExc_TabError
;
1593 PyObject
*PyExc_ReferenceError
;
1594 PyObject
*PyExc_SystemError
;
1595 PyObject
*PyExc_SystemExit
;
1596 PyObject
*PyExc_UnboundLocalError
;
1597 PyObject
*PyExc_UnicodeError
;
1598 PyObject
*PyExc_UnicodeEncodeError
;
1599 PyObject
*PyExc_UnicodeDecodeError
;
1600 PyObject
*PyExc_UnicodeTranslateError
;
1601 PyObject
*PyExc_TypeError
;
1602 PyObject
*PyExc_ValueError
;
1603 PyObject
*PyExc_ZeroDivisionError
;
1605 PyObject
*PyExc_WindowsError
;
1608 PyObject
*PyExc_VMSError
;
1611 /* Pre-computed MemoryError instance. Best to create this as early as
1612 * possibly and not wait until a MemoryError is actually raised!
1614 PyObject
*PyExc_MemoryErrorInst
;
1616 /* Predefined warning categories */
1617 PyObject
*PyExc_Warning
;
1618 PyObject
*PyExc_UserWarning
;
1619 PyObject
*PyExc_DeprecationWarning
;
1620 PyObject
*PyExc_PendingDeprecationWarning
;
1621 PyObject
*PyExc_SyntaxWarning
;
1622 PyObject
*PyExc_OverflowWarning
;
1623 PyObject
*PyExc_RuntimeWarning
;
1624 PyObject
*PyExc_FutureWarning
;
1628 /* mapping between exception names and their PyObject ** */
1632 PyObject
**base
; /* NULL == PyExc_StandardError */
1634 PyMethodDef
*methods
;
1635 int (*classinit
)(PyObject
*);
1638 * The first three classes MUST appear in exactly this order
1640 {"Exception", &PyExc_Exception
},
1641 {"StopIteration", &PyExc_StopIteration
, &PyExc_Exception
,
1642 StopIteration__doc__
},
1643 {"StandardError", &PyExc_StandardError
, &PyExc_Exception
,
1644 StandardError__doc__
},
1645 {"TypeError", &PyExc_TypeError
, 0, TypeError__doc__
},
1647 * The rest appear in depth-first order of the hierarchy
1649 {"SystemExit", &PyExc_SystemExit
, &PyExc_Exception
, SystemExit__doc__
,
1650 SystemExit_methods
},
1651 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt
, 0, KeyboardInterrupt__doc__
},
1652 {"ImportError", &PyExc_ImportError
, 0, ImportError__doc__
},
1653 {"EnvironmentError", &PyExc_EnvironmentError
, 0, EnvironmentError__doc__
,
1654 EnvironmentError_methods
},
1655 {"IOError", &PyExc_IOError
, &PyExc_EnvironmentError
, IOError__doc__
},
1656 {"OSError", &PyExc_OSError
, &PyExc_EnvironmentError
, OSError__doc__
},
1658 {"WindowsError", &PyExc_WindowsError
, &PyExc_OSError
,
1659 WindowsError__doc__
},
1660 #endif /* MS_WINDOWS */
1662 {"VMSError", &PyExc_VMSError
, &PyExc_OSError
,
1665 {"EOFError", &PyExc_EOFError
, 0, EOFError__doc__
},
1666 {"RuntimeError", &PyExc_RuntimeError
, 0, RuntimeError__doc__
},
1667 {"NotImplementedError", &PyExc_NotImplementedError
,
1668 &PyExc_RuntimeError
, NotImplementedError__doc__
},
1669 {"NameError", &PyExc_NameError
, 0, NameError__doc__
},
1670 {"UnboundLocalError", &PyExc_UnboundLocalError
, &PyExc_NameError
,
1671 UnboundLocalError__doc__
},
1672 {"AttributeError", &PyExc_AttributeError
, 0, AttributeError__doc__
},
1673 {"SyntaxError", &PyExc_SyntaxError
, 0, SyntaxError__doc__
,
1674 SyntaxError_methods
, SyntaxError__classinit__
},
1675 {"IndentationError", &PyExc_IndentationError
, &PyExc_SyntaxError
,
1676 IndentationError__doc__
},
1677 {"TabError", &PyExc_TabError
, &PyExc_IndentationError
,
1679 {"AssertionError", &PyExc_AssertionError
, 0, AssertionError__doc__
},
1680 {"LookupError", &PyExc_LookupError
, 0, LookupError__doc__
},
1681 {"IndexError", &PyExc_IndexError
, &PyExc_LookupError
,
1683 {"KeyError", &PyExc_KeyError
, &PyExc_LookupError
,
1684 KeyError__doc__
, KeyError_methods
},
1685 {"ArithmeticError", &PyExc_ArithmeticError
, 0, ArithmeticError__doc__
},
1686 {"OverflowError", &PyExc_OverflowError
, &PyExc_ArithmeticError
,
1687 OverflowError__doc__
},
1688 {"ZeroDivisionError", &PyExc_ZeroDivisionError
, &PyExc_ArithmeticError
,
1689 ZeroDivisionError__doc__
},
1690 {"FloatingPointError", &PyExc_FloatingPointError
, &PyExc_ArithmeticError
,
1691 FloatingPointError__doc__
},
1692 {"ValueError", &PyExc_ValueError
, 0, ValueError__doc__
},
1693 {"UnicodeError", &PyExc_UnicodeError
, &PyExc_ValueError
, UnicodeError__doc__
},
1694 #ifdef Py_USING_UNICODE
1695 {"UnicodeEncodeError", &PyExc_UnicodeEncodeError
, &PyExc_UnicodeError
,
1696 UnicodeEncodeError__doc__
, UnicodeEncodeError_methods
},
1697 {"UnicodeDecodeError", &PyExc_UnicodeDecodeError
, &PyExc_UnicodeError
,
1698 UnicodeDecodeError__doc__
, UnicodeDecodeError_methods
},
1699 {"UnicodeTranslateError", &PyExc_UnicodeTranslateError
, &PyExc_UnicodeError
,
1700 UnicodeTranslateError__doc__
, UnicodeTranslateError_methods
},
1702 {"ReferenceError", &PyExc_ReferenceError
, 0, ReferenceError__doc__
},
1703 {"SystemError", &PyExc_SystemError
, 0, SystemError__doc__
},
1704 {"MemoryError", &PyExc_MemoryError
, 0, MemoryError__doc__
},
1705 /* Warning categories */
1706 {"Warning", &PyExc_Warning
, &PyExc_Exception
, Warning__doc__
},
1707 {"UserWarning", &PyExc_UserWarning
, &PyExc_Warning
, UserWarning__doc__
},
1708 {"DeprecationWarning", &PyExc_DeprecationWarning
, &PyExc_Warning
,
1709 DeprecationWarning__doc__
},
1710 {"PendingDeprecationWarning", &PyExc_PendingDeprecationWarning
, &PyExc_Warning
,
1711 PendingDeprecationWarning__doc__
},
1712 {"SyntaxWarning", &PyExc_SyntaxWarning
, &PyExc_Warning
, SyntaxWarning__doc__
},
1713 {"OverflowWarning", &PyExc_OverflowWarning
, &PyExc_Warning
,
1714 OverflowWarning__doc__
},
1715 {"RuntimeWarning", &PyExc_RuntimeWarning
, &PyExc_Warning
,
1716 RuntimeWarning__doc__
},
1717 {"FutureWarning", &PyExc_FutureWarning
, &PyExc_Warning
,
1718 FutureWarning__doc__
},
1728 char *modulename
= "exceptions";
1729 int modnamesz
= strlen(modulename
);
1731 PyObject
*me
, *mydict
, *bltinmod
, *bdict
, *doc
, *args
;
1733 me
= Py_InitModule(modulename
, functions
);
1736 mydict
= PyModule_GetDict(me
);
1739 bltinmod
= PyImport_ImportModule("__builtin__");
1740 if (bltinmod
== NULL
)
1742 bdict
= PyModule_GetDict(bltinmod
);
1745 doc
= PyString_FromString(module__doc__
);
1749 i
= PyDict_SetItemString(mydict
, "__doc__", doc
);
1753 Py_FatalError("exceptions bootstrapping error.");
1757 /* This is the base class of all exceptions, so make it first. */
1758 if (make_Exception(modulename
) ||
1759 PyDict_SetItemString(mydict
, "Exception", PyExc_Exception
) ||
1760 PyDict_SetItemString(bdict
, "Exception", PyExc_Exception
))
1762 Py_FatalError("Base class `Exception' could not be created.");
1765 /* Now we can programmatically create all the remaining exceptions.
1766 * Remember to start the loop at 1 to skip Exceptions.
1768 for (i
=1; exctable
[i
].name
; i
++) {
1770 char *cname
= PyMem_NEW(char, modnamesz
+strlen(exctable
[i
].name
)+2);
1773 (void)strcpy(cname
, modulename
);
1774 (void)strcat(cname
, ".");
1775 (void)strcat(cname
, exctable
[i
].name
);
1777 if (exctable
[i
].base
== 0)
1778 base
= PyExc_StandardError
;
1780 base
= *exctable
[i
].base
;
1782 status
= make_class(exctable
[i
].exc
, base
, cname
,
1783 exctable
[i
].methods
,
1784 exctable
[i
].docstr
);
1789 Py_FatalError("Standard exception classes could not be created.");
1791 if (exctable
[i
].classinit
) {
1792 status
= (*exctable
[i
].classinit
)(*exctable
[i
].exc
);
1794 Py_FatalError("An exception class could not be initialized.");
1797 /* Now insert the class into both this module and the __builtin__
1800 if (PyDict_SetItemString(mydict
, exctable
[i
].name
, *exctable
[i
].exc
) ||
1801 PyDict_SetItemString(bdict
, exctable
[i
].name
, *exctable
[i
].exc
))
1803 Py_FatalError("Module dictionary insertion problem.");
1807 /* Now we need to pre-allocate a MemoryError instance */
1808 args
= Py_BuildValue("()");
1810 !(PyExc_MemoryErrorInst
= PyEval_CallObject(PyExc_MemoryError
, args
)))
1812 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
1816 /* We're done with __builtin__ */
1817 Py_DECREF(bltinmod
);
1826 Py_XDECREF(PyExc_MemoryErrorInst
);
1827 PyExc_MemoryErrorInst
= NULL
;
1829 for (i
=0; exctable
[i
].name
; i
++) {
1830 /* clear the class's dictionary, freeing up circular references
1831 * between the class and its methods.
1833 PyObject
* cdict
= PyObject_GetAttrString(*exctable
[i
].exc
, "__dict__");
1834 PyDict_Clear(cdict
);
1837 /* Now decref the exception class */
1838 Py_XDECREF(*exctable
[i
].exc
);
1839 *exctable
[i
].exc
= NULL
;