2 * New exceptions.c written in Iceland by Richard Jones and Georg Brandl.
4 * Thanks go to Tim Peters and Michael Hudson for debugging.
7 #define PY_SSIZE_T_CLEAN
9 #include "structmember.h"
12 #define MAKE_IT_NONE(x) (x) = Py_None; Py_INCREF(Py_None);
13 #define EXC_MODULE_NAME "exceptions."
15 /* NOTE: If the exception class hierarchy changes, don't forget to update
16 * Lib/test/exception_hierarchy.txt
19 PyDoc_STRVAR(exceptions_doc
, "Python's standard exception class hierarchy.\n\
21 Exceptions found here are defined both in the exceptions module and the\n\
22 built-in namespace. It is recommended that user-defined exceptions\n\
23 inherit from Exception. See the documentation for the exception\n\
24 inheritance hierarchy.\n\
31 BaseException_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
33 PyBaseExceptionObject
*self
;
35 self
= (PyBaseExceptionObject
*)type
->tp_alloc(type
, 0);
38 /* the dict is created on the fly in PyObject_GenericSetAttr */
39 self
->message
= self
->dict
= NULL
;
41 self
->args
= PyTuple_New(0);
47 self
->message
= PyString_FromString("");
53 return (PyObject
*)self
;
57 BaseException_init(PyBaseExceptionObject
*self
, PyObject
*args
, PyObject
*kwds
)
59 if (!_PyArg_NoKeywords(Py_TYPE(self
)->tp_name
, kwds
))
62 Py_DECREF(self
->args
);
64 Py_INCREF(self
->args
);
66 if (PyTuple_GET_SIZE(self
->args
) == 1) {
67 Py_CLEAR(self
->message
);
68 self
->message
= PyTuple_GET_ITEM(self
->args
, 0);
69 Py_INCREF(self
->message
);
75 BaseException_clear(PyBaseExceptionObject
*self
)
79 Py_CLEAR(self
->message
);
84 BaseException_dealloc(PyBaseExceptionObject
*self
)
86 _PyObject_GC_UNTRACK(self
);
87 BaseException_clear(self
);
88 Py_TYPE(self
)->tp_free((PyObject
*)self
);
92 BaseException_traverse(PyBaseExceptionObject
*self
, visitproc visit
, void *arg
)
96 Py_VISIT(self
->message
);
101 BaseException_str(PyBaseExceptionObject
*self
)
105 switch (PyTuple_GET_SIZE(self
->args
)) {
107 out
= PyString_FromString("");
110 out
= PyObject_Str(PyTuple_GET_ITEM(self
->args
, 0));
113 out
= PyObject_Str(self
->args
);
120 #ifdef Py_USING_UNICODE
122 BaseException_unicode(PyBaseExceptionObject
*self
)
126 switch (PyTuple_GET_SIZE(self
->args
)) {
128 out
= PyUnicode_FromString("");
131 out
= PyObject_Unicode(PyTuple_GET_ITEM(self
->args
, 0));
134 out
= PyObject_Unicode(self
->args
);
143 BaseException_repr(PyBaseExceptionObject
*self
)
145 PyObject
*repr_suffix
;
150 repr_suffix
= PyObject_Repr(self
->args
);
154 name
= (char *)Py_TYPE(self
)->tp_name
;
155 dot
= strrchr(name
, '.');
156 if (dot
!= NULL
) name
= dot
+1;
158 repr
= PyString_FromString(name
);
160 Py_DECREF(repr_suffix
);
164 PyString_ConcatAndDel(&repr
, repr_suffix
);
168 /* Pickling support */
170 BaseException_reduce(PyBaseExceptionObject
*self
)
172 if (self
->args
&& self
->dict
)
173 return PyTuple_Pack(3, Py_TYPE(self
), self
->args
, self
->dict
);
175 return PyTuple_Pack(2, Py_TYPE(self
), self
->args
);
179 * Needed for backward compatibility, since exceptions used to store
180 * all their attributes in the __dict__. Code is taken from cPickle's
181 * load_build function.
184 BaseException_setstate(PyObject
*self
, PyObject
*state
)
186 PyObject
*d_key
, *d_value
;
189 if (state
!= Py_None
) {
190 if (!PyDict_Check(state
)) {
191 PyErr_SetString(PyExc_TypeError
, "state is not a dictionary");
194 while (PyDict_Next(state
, &i
, &d_key
, &d_value
)) {
195 if (PyObject_SetAttr(self
, d_key
, d_value
) < 0)
203 static PyMethodDef BaseException_methods
[] = {
204 {"__reduce__", (PyCFunction
)BaseException_reduce
, METH_NOARGS
},
205 {"__setstate__", (PyCFunction
)BaseException_setstate
, METH_O
},
206 #ifdef Py_USING_UNICODE
207 {"__unicode__", (PyCFunction
)BaseException_unicode
, METH_NOARGS
},
209 {NULL
, NULL
, 0, NULL
},
215 BaseException_getitem(PyBaseExceptionObject
*self
, Py_ssize_t index
)
217 if (PyErr_WarnPy3k("__getitem__ not supported for exception "
218 "classes in 3.x; use args attribute", 1) < 0)
220 return PySequence_GetItem(self
->args
, index
);
224 BaseException_getslice(PyBaseExceptionObject
*self
,
225 Py_ssize_t start
, Py_ssize_t stop
)
227 if (PyErr_WarnPy3k("__getslice__ not supported for exception "
228 "classes in 3.x; use args attribute", 1) < 0)
230 return PySequence_GetSlice(self
->args
, start
, stop
);
233 static PySequenceMethods BaseException_as_sequence
= {
237 (ssizeargfunc
)BaseException_getitem
, /* sq_item; */
238 (ssizessizeargfunc
)BaseException_getslice
, /* sq_slice; */
239 0, /* sq_ass_item; */
240 0, /* sq_ass_slice; */
241 0, /* sq_contains; */
242 0, /* sq_inplace_concat; */
243 0 /* sq_inplace_repeat; */
247 BaseException_get_dict(PyBaseExceptionObject
*self
)
249 if (self
->dict
== NULL
) {
250 self
->dict
= PyDict_New();
254 Py_INCREF(self
->dict
);
259 BaseException_set_dict(PyBaseExceptionObject
*self
, PyObject
*val
)
262 PyErr_SetString(PyExc_TypeError
, "__dict__ may not be deleted");
265 if (!PyDict_Check(val
)) {
266 PyErr_SetString(PyExc_TypeError
, "__dict__ must be a dictionary");
269 Py_CLEAR(self
->dict
);
276 BaseException_get_args(PyBaseExceptionObject
*self
)
278 if (self
->args
== NULL
) {
282 Py_INCREF(self
->args
);
287 BaseException_set_args(PyBaseExceptionObject
*self
, PyObject
*val
)
291 PyErr_SetString(PyExc_TypeError
, "args may not be deleted");
294 seq
= PySequence_Tuple(val
);
296 Py_CLEAR(self
->args
);
302 BaseException_get_message(PyBaseExceptionObject
*self
)
305 ret
= PyErr_WarnEx(PyExc_DeprecationWarning
,
306 "BaseException.message has been deprecated as "
311 Py_INCREF(self
->message
);
312 return self
->message
;
316 BaseException_set_message(PyBaseExceptionObject
*self
, PyObject
*val
)
319 ret
= PyErr_WarnEx(PyExc_DeprecationWarning
,
320 "BaseException.message has been deprecated as "
325 Py_DECREF(self
->message
);
330 static PyGetSetDef BaseException_getset
[] = {
331 {"__dict__", (getter
)BaseException_get_dict
, (setter
)BaseException_set_dict
},
332 {"args", (getter
)BaseException_get_args
, (setter
)BaseException_set_args
},
333 {"message", (getter
)BaseException_get_message
,
334 (setter
)BaseException_set_message
},
339 static PyTypeObject _PyExc_BaseException
= {
340 PyObject_HEAD_INIT(NULL
)
342 EXC_MODULE_NAME
"BaseException", /*tp_name*/
343 sizeof(PyBaseExceptionObject
), /*tp_basicsize*/
345 (destructor
)BaseException_dealloc
, /*tp_dealloc*/
350 (reprfunc
)BaseException_repr
, /*tp_repr*/
352 &BaseException_as_sequence
, /*tp_as_sequence*/
356 (reprfunc
)BaseException_str
, /*tp_str*/
357 PyObject_GenericGetAttr
, /*tp_getattro*/
358 PyObject_GenericSetAttr
, /*tp_setattro*/
360 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
|
361 Py_TPFLAGS_BASE_EXC_SUBCLASS
, /*tp_flags*/
362 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
363 (traverseproc
)BaseException_traverse
, /* tp_traverse */
364 (inquiry
)BaseException_clear
, /* tp_clear */
365 0, /* tp_richcompare */
366 0, /* tp_weaklistoffset */
369 BaseException_methods
, /* tp_methods */
371 BaseException_getset
, /* tp_getset */
374 0, /* tp_descr_get */
375 0, /* tp_descr_set */
376 offsetof(PyBaseExceptionObject
, dict
), /* tp_dictoffset */
377 (initproc
)BaseException_init
, /* tp_init */
379 BaseException_new
, /* tp_new */
381 /* the CPython API expects exceptions to be (PyObject *) - both a hold-over
382 from the previous implmentation and also allowing Python objects to be used
384 PyObject
*PyExc_BaseException
= (PyObject
*)&_PyExc_BaseException
;
386 /* note these macros omit the last semicolon so the macro invocation may
387 * include it and not look strange.
389 #define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
390 static PyTypeObject _PyExc_ ## EXCNAME = { \
391 PyObject_HEAD_INIT(NULL) \
393 EXC_MODULE_NAME # EXCNAME, \
394 sizeof(PyBaseExceptionObject), \
395 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
396 0, 0, 0, 0, 0, 0, 0, \
397 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
398 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
399 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
400 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
401 (initproc)BaseException_init, 0, BaseException_new,\
403 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
405 #define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
406 static PyTypeObject _PyExc_ ## EXCNAME = { \
407 PyObject_HEAD_INIT(NULL) \
409 EXC_MODULE_NAME # EXCNAME, \
410 sizeof(Py ## EXCSTORE ## Object), \
411 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
413 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
414 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
415 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
416 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
417 (initproc)EXCSTORE ## _init, 0, BaseException_new,\
419 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
421 #define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDEALLOC, EXCMETHODS, EXCMEMBERS, EXCSTR, EXCDOC) \
422 static PyTypeObject _PyExc_ ## EXCNAME = { \
423 PyObject_HEAD_INIT(NULL) \
425 EXC_MODULE_NAME # EXCNAME, \
426 sizeof(Py ## EXCSTORE ## Object), 0, \
427 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
428 (reprfunc)EXCSTR, 0, 0, 0, \
429 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
430 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
431 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
432 EXCMEMBERS, 0, &_ ## EXCBASE, \
433 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
434 (initproc)EXCSTORE ## _init, 0, BaseException_new,\
436 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
440 * Exception extends BaseException
442 SimpleExtendsException(PyExc_BaseException
, Exception
,
443 "Common base class for all non-exit exceptions.");
447 * StandardError extends Exception
449 SimpleExtendsException(PyExc_Exception
, StandardError
,
450 "Base class for all standard Python exceptions that do not represent\n"
451 "interpreter exiting.");
455 * TypeError extends StandardError
457 SimpleExtendsException(PyExc_StandardError
, TypeError
,
458 "Inappropriate argument type.");
462 * StopIteration extends Exception
464 SimpleExtendsException(PyExc_Exception
, StopIteration
,
465 "Signal the end from iterator.next().");
469 * GeneratorExit extends BaseException
471 SimpleExtendsException(PyExc_BaseException
, GeneratorExit
,
472 "Request that a generator exit.");
476 * SystemExit extends BaseException
480 SystemExit_init(PySystemExitObject
*self
, PyObject
*args
, PyObject
*kwds
)
482 Py_ssize_t size
= PyTuple_GET_SIZE(args
);
484 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
489 Py_CLEAR(self
->code
);
491 self
->code
= PyTuple_GET_ITEM(args
, 0);
494 Py_INCREF(self
->code
);
499 SystemExit_clear(PySystemExitObject
*self
)
501 Py_CLEAR(self
->code
);
502 return BaseException_clear((PyBaseExceptionObject
*)self
);
506 SystemExit_dealloc(PySystemExitObject
*self
)
508 _PyObject_GC_UNTRACK(self
);
509 SystemExit_clear(self
);
510 Py_TYPE(self
)->tp_free((PyObject
*)self
);
514 SystemExit_traverse(PySystemExitObject
*self
, visitproc visit
, void *arg
)
516 Py_VISIT(self
->code
);
517 return BaseException_traverse((PyBaseExceptionObject
*)self
, visit
, arg
);
520 static PyMemberDef SystemExit_members
[] = {
521 {"code", T_OBJECT
, offsetof(PySystemExitObject
, code
), 0,
522 PyDoc_STR("exception code")},
523 {NULL
} /* Sentinel */
526 ComplexExtendsException(PyExc_BaseException
, SystemExit
, SystemExit
,
527 SystemExit_dealloc
, 0, SystemExit_members
, 0,
528 "Request to exit from the interpreter.");
531 * KeyboardInterrupt extends BaseException
533 SimpleExtendsException(PyExc_BaseException
, KeyboardInterrupt
,
534 "Program interrupted by user.");
538 * ImportError extends StandardError
540 SimpleExtendsException(PyExc_StandardError
, ImportError
,
541 "Import can't find module, or can't find name in module.");
545 * EnvironmentError extends StandardError
548 /* Where a function has a single filename, such as open() or some
549 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
550 * called, giving a third argument which is the filename. But, so
551 * that old code using in-place unpacking doesn't break, e.g.:
553 * except IOError, (errno, strerror):
555 * we hack args so that it only contains two items. This also
556 * means we need our own __str__() which prints out the filename
557 * when it was supplied.
560 EnvironmentError_init(PyEnvironmentErrorObject
*self
, PyObject
*args
,
563 PyObject
*myerrno
= NULL
, *strerror
= NULL
, *filename
= NULL
;
564 PyObject
*subslice
= NULL
;
566 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
569 if (PyTuple_GET_SIZE(args
) <= 1 || PyTuple_GET_SIZE(args
) > 3) {
573 if (!PyArg_UnpackTuple(args
, "EnvironmentError", 2, 3,
574 &myerrno
, &strerror
, &filename
)) {
577 Py_CLEAR(self
->myerrno
); /* replacing */
578 self
->myerrno
= myerrno
;
579 Py_INCREF(self
->myerrno
);
581 Py_CLEAR(self
->strerror
); /* replacing */
582 self
->strerror
= strerror
;
583 Py_INCREF(self
->strerror
);
585 /* self->filename will remain Py_None otherwise */
586 if (filename
!= NULL
) {
587 Py_CLEAR(self
->filename
); /* replacing */
588 self
->filename
= filename
;
589 Py_INCREF(self
->filename
);
591 subslice
= PyTuple_GetSlice(args
, 0, 2);
595 Py_DECREF(self
->args
); /* replacing args */
596 self
->args
= subslice
;
602 EnvironmentError_clear(PyEnvironmentErrorObject
*self
)
604 Py_CLEAR(self
->myerrno
);
605 Py_CLEAR(self
->strerror
);
606 Py_CLEAR(self
->filename
);
607 return BaseException_clear((PyBaseExceptionObject
*)self
);
611 EnvironmentError_dealloc(PyEnvironmentErrorObject
*self
)
613 _PyObject_GC_UNTRACK(self
);
614 EnvironmentError_clear(self
);
615 Py_TYPE(self
)->tp_free((PyObject
*)self
);
619 EnvironmentError_traverse(PyEnvironmentErrorObject
*self
, visitproc visit
,
622 Py_VISIT(self
->myerrno
);
623 Py_VISIT(self
->strerror
);
624 Py_VISIT(self
->filename
);
625 return BaseException_traverse((PyBaseExceptionObject
*)self
, visit
, arg
);
629 EnvironmentError_str(PyEnvironmentErrorObject
*self
)
631 PyObject
*rtnval
= NULL
;
633 if (self
->filename
) {
638 fmt
= PyString_FromString("[Errno %s] %s: %s");
642 repr
= PyObject_Repr(self
->filename
);
647 tuple
= PyTuple_New(3);
655 Py_INCREF(self
->myerrno
);
656 PyTuple_SET_ITEM(tuple
, 0, self
->myerrno
);
660 PyTuple_SET_ITEM(tuple
, 0, Py_None
);
662 if (self
->strerror
) {
663 Py_INCREF(self
->strerror
);
664 PyTuple_SET_ITEM(tuple
, 1, self
->strerror
);
668 PyTuple_SET_ITEM(tuple
, 1, Py_None
);
671 PyTuple_SET_ITEM(tuple
, 2, repr
);
673 rtnval
= PyString_Format(fmt
, tuple
);
678 else if (self
->myerrno
&& self
->strerror
) {
682 fmt
= PyString_FromString("[Errno %s] %s");
686 tuple
= PyTuple_New(2);
693 Py_INCREF(self
->myerrno
);
694 PyTuple_SET_ITEM(tuple
, 0, self
->myerrno
);
698 PyTuple_SET_ITEM(tuple
, 0, Py_None
);
700 if (self
->strerror
) {
701 Py_INCREF(self
->strerror
);
702 PyTuple_SET_ITEM(tuple
, 1, self
->strerror
);
706 PyTuple_SET_ITEM(tuple
, 1, Py_None
);
709 rtnval
= PyString_Format(fmt
, tuple
);
715 rtnval
= BaseException_str((PyBaseExceptionObject
*)self
);
720 static PyMemberDef EnvironmentError_members
[] = {
721 {"errno", T_OBJECT
, offsetof(PyEnvironmentErrorObject
, myerrno
), 0,
722 PyDoc_STR("exception errno")},
723 {"strerror", T_OBJECT
, offsetof(PyEnvironmentErrorObject
, strerror
), 0,
724 PyDoc_STR("exception strerror")},
725 {"filename", T_OBJECT
, offsetof(PyEnvironmentErrorObject
, filename
), 0,
726 PyDoc_STR("exception filename")},
727 {NULL
} /* Sentinel */
732 EnvironmentError_reduce(PyEnvironmentErrorObject
*self
)
734 PyObject
*args
= self
->args
;
735 PyObject
*res
= NULL
, *tmp
;
737 /* self->args is only the first two real arguments if there was a
738 * file name given to EnvironmentError. */
739 if (PyTuple_GET_SIZE(args
) == 2 && self
->filename
) {
740 args
= PyTuple_New(3);
741 if (!args
) return NULL
;
743 tmp
= PyTuple_GET_ITEM(self
->args
, 0);
745 PyTuple_SET_ITEM(args
, 0, tmp
);
747 tmp
= PyTuple_GET_ITEM(self
->args
, 1);
749 PyTuple_SET_ITEM(args
, 1, tmp
);
751 Py_INCREF(self
->filename
);
752 PyTuple_SET_ITEM(args
, 2, self
->filename
);
757 res
= PyTuple_Pack(3, Py_TYPE(self
), args
, self
->dict
);
759 res
= PyTuple_Pack(2, Py_TYPE(self
), args
);
765 static PyMethodDef EnvironmentError_methods
[] = {
766 {"__reduce__", (PyCFunction
)EnvironmentError_reduce
, METH_NOARGS
},
770 ComplexExtendsException(PyExc_StandardError
, EnvironmentError
,
771 EnvironmentError
, EnvironmentError_dealloc
,
772 EnvironmentError_methods
, EnvironmentError_members
,
773 EnvironmentError_str
,
774 "Base class for I/O related errors.");
778 * IOError extends EnvironmentError
780 MiddlingExtendsException(PyExc_EnvironmentError
, IOError
,
781 EnvironmentError
, "I/O operation failed.");
785 * OSError extends EnvironmentError
787 MiddlingExtendsException(PyExc_EnvironmentError
, OSError
,
788 EnvironmentError
, "OS system call failed.");
792 * WindowsError extends OSError
798 WindowsError_clear(PyWindowsErrorObject
*self
)
800 Py_CLEAR(self
->myerrno
);
801 Py_CLEAR(self
->strerror
);
802 Py_CLEAR(self
->filename
);
803 Py_CLEAR(self
->winerror
);
804 return BaseException_clear((PyBaseExceptionObject
*)self
);
808 WindowsError_dealloc(PyWindowsErrorObject
*self
)
810 _PyObject_GC_UNTRACK(self
);
811 WindowsError_clear(self
);
812 Py_TYPE(self
)->tp_free((PyObject
*)self
);
816 WindowsError_traverse(PyWindowsErrorObject
*self
, visitproc visit
, void *arg
)
818 Py_VISIT(self
->myerrno
);
819 Py_VISIT(self
->strerror
);
820 Py_VISIT(self
->filename
);
821 Py_VISIT(self
->winerror
);
822 return BaseException_traverse((PyBaseExceptionObject
*)self
, visit
, arg
);
826 WindowsError_init(PyWindowsErrorObject
*self
, PyObject
*args
, PyObject
*kwds
)
828 PyObject
*o_errcode
= NULL
;
832 if (EnvironmentError_init((PyEnvironmentErrorObject
*)self
, args
, kwds
)
836 if (self
->myerrno
== NULL
)
839 /* Set errno to the POSIX errno, and winerror to the Win32
841 errcode
= PyInt_AsLong(self
->myerrno
);
842 if (errcode
== -1 && PyErr_Occurred())
844 posix_errno
= winerror_to_errno(errcode
);
846 Py_CLEAR(self
->winerror
);
847 self
->winerror
= self
->myerrno
;
849 o_errcode
= PyInt_FromLong(posix_errno
);
853 self
->myerrno
= o_errcode
;
860 WindowsError_str(PyWindowsErrorObject
*self
)
862 PyObject
*rtnval
= NULL
;
864 if (self
->filename
) {
869 fmt
= PyString_FromString("[Error %s] %s: %s");
873 repr
= PyObject_Repr(self
->filename
);
878 tuple
= PyTuple_New(3);
885 if (self
->winerror
) {
886 Py_INCREF(self
->winerror
);
887 PyTuple_SET_ITEM(tuple
, 0, self
->winerror
);
891 PyTuple_SET_ITEM(tuple
, 0, Py_None
);
893 if (self
->strerror
) {
894 Py_INCREF(self
->strerror
);
895 PyTuple_SET_ITEM(tuple
, 1, self
->strerror
);
899 PyTuple_SET_ITEM(tuple
, 1, Py_None
);
902 PyTuple_SET_ITEM(tuple
, 2, repr
);
904 rtnval
= PyString_Format(fmt
, tuple
);
909 else if (self
->winerror
&& self
->strerror
) {
913 fmt
= PyString_FromString("[Error %s] %s");
917 tuple
= PyTuple_New(2);
923 if (self
->winerror
) {
924 Py_INCREF(self
->winerror
);
925 PyTuple_SET_ITEM(tuple
, 0, self
->winerror
);
929 PyTuple_SET_ITEM(tuple
, 0, Py_None
);
931 if (self
->strerror
) {
932 Py_INCREF(self
->strerror
);
933 PyTuple_SET_ITEM(tuple
, 1, self
->strerror
);
937 PyTuple_SET_ITEM(tuple
, 1, Py_None
);
940 rtnval
= PyString_Format(fmt
, tuple
);
946 rtnval
= EnvironmentError_str((PyEnvironmentErrorObject
*)self
);
951 static PyMemberDef WindowsError_members
[] = {
952 {"errno", T_OBJECT
, offsetof(PyWindowsErrorObject
, myerrno
), 0,
953 PyDoc_STR("POSIX exception code")},
954 {"strerror", T_OBJECT
, offsetof(PyWindowsErrorObject
, strerror
), 0,
955 PyDoc_STR("exception strerror")},
956 {"filename", T_OBJECT
, offsetof(PyWindowsErrorObject
, filename
), 0,
957 PyDoc_STR("exception filename")},
958 {"winerror", T_OBJECT
, offsetof(PyWindowsErrorObject
, winerror
), 0,
959 PyDoc_STR("Win32 exception code")},
960 {NULL
} /* Sentinel */
963 ComplexExtendsException(PyExc_OSError
, WindowsError
, WindowsError
,
964 WindowsError_dealloc
, 0, WindowsError_members
,
965 WindowsError_str
, "MS-Windows OS system call failed.");
967 #endif /* MS_WINDOWS */
971 * VMSError extends OSError (I think)
974 MiddlingExtendsException(PyExc_OSError
, VMSError
, EnvironmentError
,
975 "OpenVMS OS system call failed.");
980 * EOFError extends StandardError
982 SimpleExtendsException(PyExc_StandardError
, EOFError
,
983 "Read beyond end of file.");
987 * RuntimeError extends StandardError
989 SimpleExtendsException(PyExc_StandardError
, RuntimeError
,
990 "Unspecified run-time error.");
994 * NotImplementedError extends RuntimeError
996 SimpleExtendsException(PyExc_RuntimeError
, NotImplementedError
,
997 "Method or function hasn't been implemented yet.");
1000 * NameError extends StandardError
1002 SimpleExtendsException(PyExc_StandardError
, NameError
,
1003 "Name not found globally.");
1006 * UnboundLocalError extends NameError
1008 SimpleExtendsException(PyExc_NameError
, UnboundLocalError
,
1009 "Local name referenced but not bound to a value.");
1012 * AttributeError extends StandardError
1014 SimpleExtendsException(PyExc_StandardError
, AttributeError
,
1015 "Attribute not found.");
1019 * SyntaxError extends StandardError
1023 SyntaxError_init(PySyntaxErrorObject
*self
, PyObject
*args
, PyObject
*kwds
)
1025 PyObject
*info
= NULL
;
1026 Py_ssize_t lenargs
= PyTuple_GET_SIZE(args
);
1028 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
1032 Py_CLEAR(self
->msg
);
1033 self
->msg
= PyTuple_GET_ITEM(args
, 0);
1034 Py_INCREF(self
->msg
);
1037 info
= PyTuple_GET_ITEM(args
, 1);
1038 info
= PySequence_Tuple(info
);
1039 if (!info
) return -1;
1041 if (PyTuple_GET_SIZE(info
) != 4) {
1042 /* not a very good error message, but it's what Python 2.4 gives */
1043 PyErr_SetString(PyExc_IndexError
, "tuple index out of range");
1048 Py_CLEAR(self
->filename
);
1049 self
->filename
= PyTuple_GET_ITEM(info
, 0);
1050 Py_INCREF(self
->filename
);
1052 Py_CLEAR(self
->lineno
);
1053 self
->lineno
= PyTuple_GET_ITEM(info
, 1);
1054 Py_INCREF(self
->lineno
);
1056 Py_CLEAR(self
->offset
);
1057 self
->offset
= PyTuple_GET_ITEM(info
, 2);
1058 Py_INCREF(self
->offset
);
1060 Py_CLEAR(self
->text
);
1061 self
->text
= PyTuple_GET_ITEM(info
, 3);
1062 Py_INCREF(self
->text
);
1070 SyntaxError_clear(PySyntaxErrorObject
*self
)
1072 Py_CLEAR(self
->msg
);
1073 Py_CLEAR(self
->filename
);
1074 Py_CLEAR(self
->lineno
);
1075 Py_CLEAR(self
->offset
);
1076 Py_CLEAR(self
->text
);
1077 Py_CLEAR(self
->print_file_and_line
);
1078 return BaseException_clear((PyBaseExceptionObject
*)self
);
1082 SyntaxError_dealloc(PySyntaxErrorObject
*self
)
1084 _PyObject_GC_UNTRACK(self
);
1085 SyntaxError_clear(self
);
1086 Py_TYPE(self
)->tp_free((PyObject
*)self
);
1090 SyntaxError_traverse(PySyntaxErrorObject
*self
, visitproc visit
, void *arg
)
1092 Py_VISIT(self
->msg
);
1093 Py_VISIT(self
->filename
);
1094 Py_VISIT(self
->lineno
);
1095 Py_VISIT(self
->offset
);
1096 Py_VISIT(self
->text
);
1097 Py_VISIT(self
->print_file_and_line
);
1098 return BaseException_traverse((PyBaseExceptionObject
*)self
, visit
, arg
);
1101 /* This is called "my_basename" instead of just "basename" to avoid name
1102 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1103 defined, and Python does define that. */
1105 my_basename(char *name
)
1108 char *result
= name
;
1112 while (*cp
!= '\0') {
1122 SyntaxError_str(PySyntaxErrorObject
*self
)
1126 int have_filename
= 0;
1127 int have_lineno
= 0;
1128 char *buffer
= NULL
;
1132 str
= PyObject_Str(self
->msg
);
1134 str
= PyObject_Str(Py_None
);
1135 if (!str
) return NULL
;
1136 /* Don't fiddle with non-string return (shouldn't happen anyway) */
1137 if (!PyString_Check(str
)) return str
;
1139 /* XXX -- do all the additional formatting with filename and
1142 have_filename
= (self
->filename
!= NULL
) &&
1143 PyString_Check(self
->filename
);
1144 have_lineno
= (self
->lineno
!= NULL
) && PyInt_Check(self
->lineno
);
1146 if (!have_filename
&& !have_lineno
)
1149 bufsize
= PyString_GET_SIZE(str
) + 64;
1151 bufsize
+= PyString_GET_SIZE(self
->filename
);
1153 buffer
= PyMem_MALLOC(bufsize
);
1157 if (have_filename
&& have_lineno
)
1158 PyOS_snprintf(buffer
, bufsize
, "%s (%s, line %ld)",
1159 PyString_AS_STRING(str
),
1160 my_basename(PyString_AS_STRING(self
->filename
)),
1161 PyInt_AsLong(self
->lineno
));
1162 else if (have_filename
)
1163 PyOS_snprintf(buffer
, bufsize
, "%s (%s)",
1164 PyString_AS_STRING(str
),
1165 my_basename(PyString_AS_STRING(self
->filename
)));
1166 else /* only have_lineno */
1167 PyOS_snprintf(buffer
, bufsize
, "%s (line %ld)",
1168 PyString_AS_STRING(str
),
1169 PyInt_AsLong(self
->lineno
));
1171 result
= PyString_FromString(buffer
);
1181 static PyMemberDef SyntaxError_members
[] = {
1182 {"msg", T_OBJECT
, offsetof(PySyntaxErrorObject
, msg
), 0,
1183 PyDoc_STR("exception msg")},
1184 {"filename", T_OBJECT
, offsetof(PySyntaxErrorObject
, filename
), 0,
1185 PyDoc_STR("exception filename")},
1186 {"lineno", T_OBJECT
, offsetof(PySyntaxErrorObject
, lineno
), 0,
1187 PyDoc_STR("exception lineno")},
1188 {"offset", T_OBJECT
, offsetof(PySyntaxErrorObject
, offset
), 0,
1189 PyDoc_STR("exception offset")},
1190 {"text", T_OBJECT
, offsetof(PySyntaxErrorObject
, text
), 0,
1191 PyDoc_STR("exception text")},
1192 {"print_file_and_line", T_OBJECT
,
1193 offsetof(PySyntaxErrorObject
, print_file_and_line
), 0,
1194 PyDoc_STR("exception print_file_and_line")},
1195 {NULL
} /* Sentinel */
1198 ComplexExtendsException(PyExc_StandardError
, SyntaxError
, SyntaxError
,
1199 SyntaxError_dealloc
, 0, SyntaxError_members
,
1200 SyntaxError_str
, "Invalid syntax.");
1204 * IndentationError extends SyntaxError
1206 MiddlingExtendsException(PyExc_SyntaxError
, IndentationError
, SyntaxError
,
1207 "Improper indentation.");
1211 * TabError extends IndentationError
1213 MiddlingExtendsException(PyExc_IndentationError
, TabError
, SyntaxError
,
1214 "Improper mixture of spaces and tabs.");
1218 * LookupError extends StandardError
1220 SimpleExtendsException(PyExc_StandardError
, LookupError
,
1221 "Base class for lookup errors.");
1225 * IndexError extends LookupError
1227 SimpleExtendsException(PyExc_LookupError
, IndexError
,
1228 "Sequence index out of range.");
1232 * KeyError extends LookupError
1235 KeyError_str(PyBaseExceptionObject
*self
)
1237 /* If args is a tuple of exactly one item, apply repr to args[0].
1238 This is done so that e.g. the exception raised by {}[''] prints
1240 rather than the confusing
1242 alone. The downside is that if KeyError is raised with an explanatory
1243 string, that string will be displayed in quotes. Too bad.
1244 If args is anything else, use the default BaseException__str__().
1246 if (PyTuple_GET_SIZE(self
->args
) == 1) {
1247 return PyObject_Repr(PyTuple_GET_ITEM(self
->args
, 0));
1249 return BaseException_str(self
);
1252 ComplexExtendsException(PyExc_LookupError
, KeyError
, BaseException
,
1253 0, 0, 0, KeyError_str
, "Mapping key not found.");
1257 * ValueError extends StandardError
1259 SimpleExtendsException(PyExc_StandardError
, ValueError
,
1260 "Inappropriate argument value (of correct type).");
1263 * UnicodeError extends ValueError
1266 SimpleExtendsException(PyExc_ValueError
, UnicodeError
,
1267 "Unicode related error.");
1269 #ifdef Py_USING_UNICODE
1271 get_string(PyObject
*attr
, const char *name
)
1274 PyErr_Format(PyExc_TypeError
, "%.200s attribute not set", name
);
1278 if (!PyString_Check(attr
)) {
1279 PyErr_Format(PyExc_TypeError
, "%.200s attribute must be str", name
);
1288 set_string(PyObject
**attr
, const char *value
)
1290 PyObject
*obj
= PyString_FromString(value
);
1300 get_unicode(PyObject
*attr
, const char *name
)
1303 PyErr_Format(PyExc_TypeError
, "%.200s attribute not set", name
);
1307 if (!PyUnicode_Check(attr
)) {
1308 PyErr_Format(PyExc_TypeError
,
1309 "%.200s attribute must be unicode", name
);
1317 PyUnicodeEncodeError_GetEncoding(PyObject
*exc
)
1319 return get_string(((PyUnicodeErrorObject
*)exc
)->encoding
, "encoding");
1323 PyUnicodeDecodeError_GetEncoding(PyObject
*exc
)
1325 return get_string(((PyUnicodeErrorObject
*)exc
)->encoding
, "encoding");
1329 PyUnicodeEncodeError_GetObject(PyObject
*exc
)
1331 return get_unicode(((PyUnicodeErrorObject
*)exc
)->object
, "object");
1335 PyUnicodeDecodeError_GetObject(PyObject
*exc
)
1337 return get_string(((PyUnicodeErrorObject
*)exc
)->object
, "object");
1341 PyUnicodeTranslateError_GetObject(PyObject
*exc
)
1343 return get_unicode(((PyUnicodeErrorObject
*)exc
)->object
, "object");
1347 PyUnicodeEncodeError_GetStart(PyObject
*exc
, Py_ssize_t
*start
)
1350 PyObject
*obj
= get_unicode(((PyUnicodeErrorObject
*)exc
)->object
,
1354 *start
= ((PyUnicodeErrorObject
*)exc
)->start
;
1355 size
= PyUnicode_GET_SIZE(obj
);
1357 *start
= 0; /*XXX check for values <0*/
1366 PyUnicodeDecodeError_GetStart(PyObject
*exc
, Py_ssize_t
*start
)
1369 PyObject
*obj
= get_string(((PyUnicodeErrorObject
*)exc
)->object
,
1373 size
= PyString_GET_SIZE(obj
);
1374 *start
= ((PyUnicodeErrorObject
*)exc
)->start
;
1385 PyUnicodeTranslateError_GetStart(PyObject
*exc
, Py_ssize_t
*start
)
1387 return PyUnicodeEncodeError_GetStart(exc
, start
);
1392 PyUnicodeEncodeError_SetStart(PyObject
*exc
, Py_ssize_t start
)
1394 ((PyUnicodeErrorObject
*)exc
)->start
= start
;
1400 PyUnicodeDecodeError_SetStart(PyObject
*exc
, Py_ssize_t start
)
1402 ((PyUnicodeErrorObject
*)exc
)->start
= start
;
1408 PyUnicodeTranslateError_SetStart(PyObject
*exc
, Py_ssize_t start
)
1410 ((PyUnicodeErrorObject
*)exc
)->start
= start
;
1416 PyUnicodeEncodeError_GetEnd(PyObject
*exc
, Py_ssize_t
*end
)
1419 PyObject
*obj
= get_unicode(((PyUnicodeErrorObject
*)exc
)->object
,
1423 *end
= ((PyUnicodeErrorObject
*)exc
)->end
;
1424 size
= PyUnicode_GET_SIZE(obj
);
1435 PyUnicodeDecodeError_GetEnd(PyObject
*exc
, Py_ssize_t
*end
)
1438 PyObject
*obj
= get_string(((PyUnicodeErrorObject
*)exc
)->object
,
1442 *end
= ((PyUnicodeErrorObject
*)exc
)->end
;
1443 size
= PyString_GET_SIZE(obj
);
1454 PyUnicodeTranslateError_GetEnd(PyObject
*exc
, Py_ssize_t
*start
)
1456 return PyUnicodeEncodeError_GetEnd(exc
, start
);
1461 PyUnicodeEncodeError_SetEnd(PyObject
*exc
, Py_ssize_t end
)
1463 ((PyUnicodeErrorObject
*)exc
)->end
= end
;
1469 PyUnicodeDecodeError_SetEnd(PyObject
*exc
, Py_ssize_t end
)
1471 ((PyUnicodeErrorObject
*)exc
)->end
= end
;
1477 PyUnicodeTranslateError_SetEnd(PyObject
*exc
, Py_ssize_t end
)
1479 ((PyUnicodeErrorObject
*)exc
)->end
= end
;
1484 PyUnicodeEncodeError_GetReason(PyObject
*exc
)
1486 return get_string(((PyUnicodeErrorObject
*)exc
)->reason
, "reason");
1491 PyUnicodeDecodeError_GetReason(PyObject
*exc
)
1493 return get_string(((PyUnicodeErrorObject
*)exc
)->reason
, "reason");
1498 PyUnicodeTranslateError_GetReason(PyObject
*exc
)
1500 return get_string(((PyUnicodeErrorObject
*)exc
)->reason
, "reason");
1505 PyUnicodeEncodeError_SetReason(PyObject
*exc
, const char *reason
)
1507 return set_string(&((PyUnicodeErrorObject
*)exc
)->reason
, reason
);
1512 PyUnicodeDecodeError_SetReason(PyObject
*exc
, const char *reason
)
1514 return set_string(&((PyUnicodeErrorObject
*)exc
)->reason
, reason
);
1519 PyUnicodeTranslateError_SetReason(PyObject
*exc
, const char *reason
)
1521 return set_string(&((PyUnicodeErrorObject
*)exc
)->reason
, reason
);
1526 UnicodeError_init(PyUnicodeErrorObject
*self
, PyObject
*args
, PyObject
*kwds
,
1527 PyTypeObject
*objecttype
)
1529 Py_CLEAR(self
->encoding
);
1530 Py_CLEAR(self
->object
);
1531 Py_CLEAR(self
->reason
);
1533 if (!PyArg_ParseTuple(args
, "O!O!nnO!",
1534 &PyString_Type
, &self
->encoding
,
1535 objecttype
, &self
->object
,
1538 &PyString_Type
, &self
->reason
)) {
1539 self
->encoding
= self
->object
= self
->reason
= NULL
;
1543 Py_INCREF(self
->encoding
);
1544 Py_INCREF(self
->object
);
1545 Py_INCREF(self
->reason
);
1551 UnicodeError_clear(PyUnicodeErrorObject
*self
)
1553 Py_CLEAR(self
->encoding
);
1554 Py_CLEAR(self
->object
);
1555 Py_CLEAR(self
->reason
);
1556 return BaseException_clear((PyBaseExceptionObject
*)self
);
1560 UnicodeError_dealloc(PyUnicodeErrorObject
*self
)
1562 _PyObject_GC_UNTRACK(self
);
1563 UnicodeError_clear(self
);
1564 Py_TYPE(self
)->tp_free((PyObject
*)self
);
1568 UnicodeError_traverse(PyUnicodeErrorObject
*self
, visitproc visit
, void *arg
)
1570 Py_VISIT(self
->encoding
);
1571 Py_VISIT(self
->object
);
1572 Py_VISIT(self
->reason
);
1573 return BaseException_traverse((PyBaseExceptionObject
*)self
, visit
, arg
);
1576 static PyMemberDef UnicodeError_members
[] = {
1577 {"encoding", T_OBJECT
, offsetof(PyUnicodeErrorObject
, encoding
), 0,
1578 PyDoc_STR("exception encoding")},
1579 {"object", T_OBJECT
, offsetof(PyUnicodeErrorObject
, object
), 0,
1580 PyDoc_STR("exception object")},
1581 {"start", T_PYSSIZET
, offsetof(PyUnicodeErrorObject
, start
), 0,
1582 PyDoc_STR("exception start")},
1583 {"end", T_PYSSIZET
, offsetof(PyUnicodeErrorObject
, end
), 0,
1584 PyDoc_STR("exception end")},
1585 {"reason", T_OBJECT
, offsetof(PyUnicodeErrorObject
, reason
), 0,
1586 PyDoc_STR("exception reason")},
1587 {NULL
} /* Sentinel */
1592 * UnicodeEncodeError extends UnicodeError
1596 UnicodeEncodeError_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1598 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
1600 return UnicodeError_init((PyUnicodeErrorObject
*)self
, args
,
1601 kwds
, &PyUnicode_Type
);
1605 UnicodeEncodeError_str(PyObject
*self
)
1607 PyUnicodeErrorObject
*uself
= (PyUnicodeErrorObject
*)self
;
1609 if (uself
->end
==uself
->start
+1) {
1610 int badchar
= (int)PyUnicode_AS_UNICODE(uself
->object
)[uself
->start
];
1611 char badchar_str
[20];
1612 if (badchar
<= 0xff)
1613 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "x%02x", badchar
);
1614 else if (badchar
<= 0xffff)
1615 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "u%04x", badchar
);
1617 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "U%08x", badchar
);
1618 return PyString_FromFormat(
1619 "'%.400s' codec can't encode character u'\\%s' in position %zd: %.400s",
1620 PyString_AS_STRING(uself
->encoding
),
1623 PyString_AS_STRING(uself
->reason
)
1626 return PyString_FromFormat(
1627 "'%.400s' codec can't encode characters in position %zd-%zd: %.400s",
1628 PyString_AS_STRING(uself
->encoding
),
1631 PyString_AS_STRING(uself
->reason
)
1635 static PyTypeObject _PyExc_UnicodeEncodeError
= {
1636 PyObject_HEAD_INIT(NULL
)
1638 EXC_MODULE_NAME
"UnicodeEncodeError",
1639 sizeof(PyUnicodeErrorObject
), 0,
1640 (destructor
)UnicodeError_dealloc
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1641 (reprfunc
)UnicodeEncodeError_str
, 0, 0, 0,
1642 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
1643 PyDoc_STR("Unicode encoding error."), (traverseproc
)UnicodeError_traverse
,
1644 (inquiry
)UnicodeError_clear
, 0, 0, 0, 0, 0, UnicodeError_members
,
1645 0, &_PyExc_UnicodeError
, 0, 0, 0, offsetof(PyUnicodeErrorObject
, dict
),
1646 (initproc
)UnicodeEncodeError_init
, 0, BaseException_new
,
1648 PyObject
*PyExc_UnicodeEncodeError
= (PyObject
*)&_PyExc_UnicodeEncodeError
;
1651 PyUnicodeEncodeError_Create(
1652 const char *encoding
, const Py_UNICODE
*object
, Py_ssize_t length
,
1653 Py_ssize_t start
, Py_ssize_t end
, const char *reason
)
1655 return PyObject_CallFunction(PyExc_UnicodeEncodeError
, "su#nns",
1656 encoding
, object
, length
, start
, end
, reason
);
1661 * UnicodeDecodeError extends UnicodeError
1665 UnicodeDecodeError_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1667 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
1669 return UnicodeError_init((PyUnicodeErrorObject
*)self
, args
,
1670 kwds
, &PyString_Type
);
1674 UnicodeDecodeError_str(PyObject
*self
)
1676 PyUnicodeErrorObject
*uself
= (PyUnicodeErrorObject
*)self
;
1678 if (uself
->end
==uself
->start
+1) {
1679 /* FromFormat does not support %02x, so format that separately */
1681 PyOS_snprintf(byte
, sizeof(byte
), "%02x",
1682 ((int)PyString_AS_STRING(uself
->object
)[uself
->start
])&0xff);
1683 return PyString_FromFormat(
1684 "'%.400s' codec can't decode byte 0x%s in position %zd: %.400s",
1685 PyString_AS_STRING(uself
->encoding
),
1688 PyString_AS_STRING(uself
->reason
)
1691 return PyString_FromFormat(
1692 "'%.400s' codec can't decode bytes in position %zd-%zd: %.400s",
1693 PyString_AS_STRING(uself
->encoding
),
1696 PyString_AS_STRING(uself
->reason
)
1700 static PyTypeObject _PyExc_UnicodeDecodeError
= {
1701 PyObject_HEAD_INIT(NULL
)
1703 EXC_MODULE_NAME
"UnicodeDecodeError",
1704 sizeof(PyUnicodeErrorObject
), 0,
1705 (destructor
)UnicodeError_dealloc
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1706 (reprfunc
)UnicodeDecodeError_str
, 0, 0, 0,
1707 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
1708 PyDoc_STR("Unicode decoding error."), (traverseproc
)UnicodeError_traverse
,
1709 (inquiry
)UnicodeError_clear
, 0, 0, 0, 0, 0, UnicodeError_members
,
1710 0, &_PyExc_UnicodeError
, 0, 0, 0, offsetof(PyUnicodeErrorObject
, dict
),
1711 (initproc
)UnicodeDecodeError_init
, 0, BaseException_new
,
1713 PyObject
*PyExc_UnicodeDecodeError
= (PyObject
*)&_PyExc_UnicodeDecodeError
;
1716 PyUnicodeDecodeError_Create(
1717 const char *encoding
, const char *object
, Py_ssize_t length
,
1718 Py_ssize_t start
, Py_ssize_t end
, const char *reason
)
1720 assert(length
< INT_MAX
);
1721 assert(start
< INT_MAX
);
1722 assert(end
< INT_MAX
);
1723 return PyObject_CallFunction(PyExc_UnicodeDecodeError
, "ss#nns",
1724 encoding
, object
, length
, start
, end
, reason
);
1729 * UnicodeTranslateError extends UnicodeError
1733 UnicodeTranslateError_init(PyUnicodeErrorObject
*self
, PyObject
*args
,
1736 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
1739 Py_CLEAR(self
->object
);
1740 Py_CLEAR(self
->reason
);
1742 if (!PyArg_ParseTuple(args
, "O!nnO!",
1743 &PyUnicode_Type
, &self
->object
,
1746 &PyString_Type
, &self
->reason
)) {
1747 self
->object
= self
->reason
= NULL
;
1751 Py_INCREF(self
->object
);
1752 Py_INCREF(self
->reason
);
1759 UnicodeTranslateError_str(PyObject
*self
)
1761 PyUnicodeErrorObject
*uself
= (PyUnicodeErrorObject
*)self
;
1763 if (uself
->end
==uself
->start
+1) {
1764 int badchar
= (int)PyUnicode_AS_UNICODE(uself
->object
)[uself
->start
];
1765 char badchar_str
[20];
1766 if (badchar
<= 0xff)
1767 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "x%02x", badchar
);
1768 else if (badchar
<= 0xffff)
1769 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "u%04x", badchar
);
1771 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "U%08x", badchar
);
1772 return PyString_FromFormat(
1773 "can't translate character u'\\%s' in position %zd: %.400s",
1776 PyString_AS_STRING(uself
->reason
)
1779 return PyString_FromFormat(
1780 "can't translate characters in position %zd-%zd: %.400s",
1783 PyString_AS_STRING(uself
->reason
)
1787 static PyTypeObject _PyExc_UnicodeTranslateError
= {
1788 PyObject_HEAD_INIT(NULL
)
1790 EXC_MODULE_NAME
"UnicodeTranslateError",
1791 sizeof(PyUnicodeErrorObject
), 0,
1792 (destructor
)UnicodeError_dealloc
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1793 (reprfunc
)UnicodeTranslateError_str
, 0, 0, 0,
1794 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
1795 PyDoc_STR("Unicode translation error."), (traverseproc
)UnicodeError_traverse
,
1796 (inquiry
)UnicodeError_clear
, 0, 0, 0, 0, 0, UnicodeError_members
,
1797 0, &_PyExc_UnicodeError
, 0, 0, 0, offsetof(PyUnicodeErrorObject
, dict
),
1798 (initproc
)UnicodeTranslateError_init
, 0, BaseException_new
,
1800 PyObject
*PyExc_UnicodeTranslateError
= (PyObject
*)&_PyExc_UnicodeTranslateError
;
1803 PyUnicodeTranslateError_Create(
1804 const Py_UNICODE
*object
, Py_ssize_t length
,
1805 Py_ssize_t start
, Py_ssize_t end
, const char *reason
)
1807 return PyObject_CallFunction(PyExc_UnicodeTranslateError
, "u#nns",
1808 object
, length
, start
, end
, reason
);
1814 * AssertionError extends StandardError
1816 SimpleExtendsException(PyExc_StandardError
, AssertionError
,
1817 "Assertion failed.");
1821 * ArithmeticError extends StandardError
1823 SimpleExtendsException(PyExc_StandardError
, ArithmeticError
,
1824 "Base class for arithmetic errors.");
1828 * FloatingPointError extends ArithmeticError
1830 SimpleExtendsException(PyExc_ArithmeticError
, FloatingPointError
,
1831 "Floating point operation failed.");
1835 * OverflowError extends ArithmeticError
1837 SimpleExtendsException(PyExc_ArithmeticError
, OverflowError
,
1838 "Result too large to be represented.");
1842 * ZeroDivisionError extends ArithmeticError
1844 SimpleExtendsException(PyExc_ArithmeticError
, ZeroDivisionError
,
1845 "Second argument to a division or modulo operation was zero.");
1849 * SystemError extends StandardError
1851 SimpleExtendsException(PyExc_StandardError
, SystemError
,
1852 "Internal error in the Python interpreter.\n"
1854 "Please report this to the Python maintainer, along with the traceback,\n"
1855 "the Python version, and the hardware/OS platform and version.");
1859 * ReferenceError extends StandardError
1861 SimpleExtendsException(PyExc_StandardError
, ReferenceError
,
1862 "Weak ref proxy used after referent went away.");
1866 * MemoryError extends StandardError
1868 SimpleExtendsException(PyExc_StandardError
, MemoryError
, "Out of memory.");
1871 * BufferError extends StandardError
1873 SimpleExtendsException(PyExc_StandardError
, BufferError
, "Buffer error.");
1876 /* Warning category docstrings */
1879 * Warning extends Exception
1881 SimpleExtendsException(PyExc_Exception
, Warning
,
1882 "Base class for warning categories.");
1886 * UserWarning extends Warning
1888 SimpleExtendsException(PyExc_Warning
, UserWarning
,
1889 "Base class for warnings generated by user code.");
1893 * DeprecationWarning extends Warning
1895 SimpleExtendsException(PyExc_Warning
, DeprecationWarning
,
1896 "Base class for warnings about deprecated features.");
1900 * PendingDeprecationWarning extends Warning
1902 SimpleExtendsException(PyExc_Warning
, PendingDeprecationWarning
,
1903 "Base class for warnings about features which will be deprecated\n"
1908 * SyntaxWarning extends Warning
1910 SimpleExtendsException(PyExc_Warning
, SyntaxWarning
,
1911 "Base class for warnings about dubious syntax.");
1915 * RuntimeWarning extends Warning
1917 SimpleExtendsException(PyExc_Warning
, RuntimeWarning
,
1918 "Base class for warnings about dubious runtime behavior.");
1922 * FutureWarning extends Warning
1924 SimpleExtendsException(PyExc_Warning
, FutureWarning
,
1925 "Base class for warnings about constructs that will change semantically\n"
1930 * ImportWarning extends Warning
1932 SimpleExtendsException(PyExc_Warning
, ImportWarning
,
1933 "Base class for warnings about probable mistakes in module imports");
1937 * UnicodeWarning extends Warning
1939 SimpleExtendsException(PyExc_Warning
, UnicodeWarning
,
1940 "Base class for warnings about Unicode related problems, mostly\n"
1941 "related to conversion problems.");
1944 * BytesWarning extends Warning
1946 SimpleExtendsException(PyExc_Warning
, BytesWarning
,
1947 "Base class for warnings about bytes and buffer related problems, mostly\n"
1948 "related to conversion from str or comparing to str.");
1950 /* Pre-computed MemoryError instance. Best to create this as early as
1951 * possible and not wait until a MemoryError is actually raised!
1953 PyObject
*PyExc_MemoryErrorInst
=NULL
;
1955 /* Pre-computed RuntimeError instance for when recursion depth is reached.
1956 Meant to be used when normalizing the exception for exceeding the recursion
1957 depth will cause its own infinite recursion.
1959 PyObject
*PyExc_RecursionErrorInst
= NULL
;
1961 /* module global functions */
1962 static PyMethodDef functions
[] = {
1967 #define PRE_INIT(TYPE) if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
1968 Py_FatalError("exceptions bootstrapping error.");
1970 #define POST_INIT(TYPE) Py_INCREF(PyExc_ ## TYPE); \
1971 PyModule_AddObject(m, # TYPE, PyExc_ ## TYPE); \
1972 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
1973 Py_FatalError("Module dictionary insertion problem.");
1975 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
1976 /* crt variable checking in VisualStudio .NET 2005 */
1979 static int prevCrtReportMode
;
1980 static _invalid_parameter_handler prevCrtHandler
;
1982 /* Invalid parameter handler. Sets a ValueError exception */
1984 InvalidParameterHandler(
1985 const wchar_t * expression
,
1986 const wchar_t * function
,
1987 const wchar_t * file
,
1989 uintptr_t pReserved
)
1991 /* Do nothing, allow execution to continue. Usually this
1992 * means that the CRT will set errno to EINVAL
2001 PyObject
*m
, *bltinmod
, *bdict
;
2003 PRE_INIT(BaseException
)
2005 PRE_INIT(StandardError
)
2007 PRE_INIT(StopIteration
)
2008 PRE_INIT(GeneratorExit
)
2009 PRE_INIT(SystemExit
)
2010 PRE_INIT(KeyboardInterrupt
)
2011 PRE_INIT(ImportError
)
2012 PRE_INIT(EnvironmentError
)
2016 PRE_INIT(WindowsError
)
2022 PRE_INIT(RuntimeError
)
2023 PRE_INIT(NotImplementedError
)
2025 PRE_INIT(UnboundLocalError
)
2026 PRE_INIT(AttributeError
)
2027 PRE_INIT(SyntaxError
)
2028 PRE_INIT(IndentationError
)
2030 PRE_INIT(LookupError
)
2031 PRE_INIT(IndexError
)
2033 PRE_INIT(ValueError
)
2034 PRE_INIT(UnicodeError
)
2035 #ifdef Py_USING_UNICODE
2036 PRE_INIT(UnicodeEncodeError
)
2037 PRE_INIT(UnicodeDecodeError
)
2038 PRE_INIT(UnicodeTranslateError
)
2040 PRE_INIT(AssertionError
)
2041 PRE_INIT(ArithmeticError
)
2042 PRE_INIT(FloatingPointError
)
2043 PRE_INIT(OverflowError
)
2044 PRE_INIT(ZeroDivisionError
)
2045 PRE_INIT(SystemError
)
2046 PRE_INIT(ReferenceError
)
2047 PRE_INIT(MemoryError
)
2048 PRE_INIT(BufferError
)
2050 PRE_INIT(UserWarning
)
2051 PRE_INIT(DeprecationWarning
)
2052 PRE_INIT(PendingDeprecationWarning
)
2053 PRE_INIT(SyntaxWarning
)
2054 PRE_INIT(RuntimeWarning
)
2055 PRE_INIT(FutureWarning
)
2056 PRE_INIT(ImportWarning
)
2057 PRE_INIT(UnicodeWarning
)
2058 PRE_INIT(BytesWarning
)
2060 m
= Py_InitModule4("exceptions", functions
, exceptions_doc
,
2061 (PyObject
*)NULL
, PYTHON_API_VERSION
);
2062 if (m
== NULL
) return;
2064 bltinmod
= PyImport_ImportModule("__builtin__");
2065 if (bltinmod
== NULL
)
2066 Py_FatalError("exceptions bootstrapping error.");
2067 bdict
= PyModule_GetDict(bltinmod
);
2069 Py_FatalError("exceptions bootstrapping error.");
2071 POST_INIT(BaseException
)
2072 POST_INIT(Exception
)
2073 POST_INIT(StandardError
)
2074 POST_INIT(TypeError
)
2075 POST_INIT(StopIteration
)
2076 POST_INIT(GeneratorExit
)
2077 POST_INIT(SystemExit
)
2078 POST_INIT(KeyboardInterrupt
)
2079 POST_INIT(ImportError
)
2080 POST_INIT(EnvironmentError
)
2084 POST_INIT(WindowsError
)
2090 POST_INIT(RuntimeError
)
2091 POST_INIT(NotImplementedError
)
2092 POST_INIT(NameError
)
2093 POST_INIT(UnboundLocalError
)
2094 POST_INIT(AttributeError
)
2095 POST_INIT(SyntaxError
)
2096 POST_INIT(IndentationError
)
2098 POST_INIT(LookupError
)
2099 POST_INIT(IndexError
)
2101 POST_INIT(ValueError
)
2102 POST_INIT(UnicodeError
)
2103 #ifdef Py_USING_UNICODE
2104 POST_INIT(UnicodeEncodeError
)
2105 POST_INIT(UnicodeDecodeError
)
2106 POST_INIT(UnicodeTranslateError
)
2108 POST_INIT(AssertionError
)
2109 POST_INIT(ArithmeticError
)
2110 POST_INIT(FloatingPointError
)
2111 POST_INIT(OverflowError
)
2112 POST_INIT(ZeroDivisionError
)
2113 POST_INIT(SystemError
)
2114 POST_INIT(ReferenceError
)
2115 POST_INIT(MemoryError
)
2116 POST_INIT(BufferError
)
2118 POST_INIT(UserWarning
)
2119 POST_INIT(DeprecationWarning
)
2120 POST_INIT(PendingDeprecationWarning
)
2121 POST_INIT(SyntaxWarning
)
2122 POST_INIT(RuntimeWarning
)
2123 POST_INIT(FutureWarning
)
2124 POST_INIT(ImportWarning
)
2125 POST_INIT(UnicodeWarning
)
2126 POST_INIT(BytesWarning
)
2128 PyExc_MemoryErrorInst
= BaseException_new(&_PyExc_MemoryError
, NULL
, NULL
);
2129 if (!PyExc_MemoryErrorInst
)
2130 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
2132 PyExc_RecursionErrorInst
= BaseException_new(&_PyExc_RuntimeError
, NULL
, NULL
);
2133 if (!PyExc_RecursionErrorInst
)
2134 Py_FatalError("Cannot pre-allocate RuntimeError instance for "
2135 "recursion errors");
2137 PyBaseExceptionObject
*err_inst
=
2138 (PyBaseExceptionObject
*)PyExc_RecursionErrorInst
;
2139 PyObject
*args_tuple
;
2140 PyObject
*exc_message
;
2141 exc_message
= PyString_FromString("maximum recursion depth exceeded");
2143 Py_FatalError("cannot allocate argument for RuntimeError "
2145 args_tuple
= PyTuple_Pack(1, exc_message
);
2147 Py_FatalError("cannot allocate tuple for RuntimeError "
2149 Py_DECREF(exc_message
);
2150 if (BaseException_init(err_inst
, args_tuple
, NULL
))
2151 Py_FatalError("init of pre-allocated RuntimeError failed");
2152 Py_DECREF(args_tuple
);
2155 Py_DECREF(bltinmod
);
2157 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
2158 /* Set CRT argument error handler */
2159 prevCrtHandler
= _set_invalid_parameter_handler(InvalidParameterHandler
);
2160 /* turn off assertions in debug mode */
2161 prevCrtReportMode
= _CrtSetReportMode(_CRT_ASSERT
, 0);
2168 Py_XDECREF(PyExc_MemoryErrorInst
);
2169 PyExc_MemoryErrorInst
= NULL
;
2170 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
2171 /* reset CRT error handling */
2172 _set_invalid_parameter_handler(prevCrtHandler
);
2173 _CrtSetReportMode(_CRT_ASSERT
, prevCrtReportMode
);