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);
36 /* the dict is created on the fly in PyObject_GenericSetAttr */
37 self
->message
= self
->dict
= NULL
;
39 self
->args
= PyTuple_New(0);
45 self
->message
= PyString_FromString("");
51 return (PyObject
*)self
;
55 BaseException_init(PyBaseExceptionObject
*self
, PyObject
*args
, PyObject
*kwds
)
57 if (!_PyArg_NoKeywords(self
->ob_type
->tp_name
, kwds
))
60 Py_DECREF(self
->args
);
62 Py_INCREF(self
->args
);
64 if (PyTuple_GET_SIZE(self
->args
) == 1) {
65 Py_CLEAR(self
->message
);
66 self
->message
= PyTuple_GET_ITEM(self
->args
, 0);
67 Py_INCREF(self
->message
);
73 BaseException_clear(PyBaseExceptionObject
*self
)
77 Py_CLEAR(self
->message
);
82 BaseException_dealloc(PyBaseExceptionObject
*self
)
84 BaseException_clear(self
);
85 self
->ob_type
->tp_free((PyObject
*)self
);
89 BaseException_traverse(PyBaseExceptionObject
*self
, visitproc visit
, void *arg
)
93 Py_VISIT(self
->message
);
98 BaseException_str(PyBaseExceptionObject
*self
)
102 switch (PyTuple_GET_SIZE(self
->args
)) {
104 out
= PyString_FromString("");
107 out
= PyObject_Str(PyTuple_GET_ITEM(self
->args
, 0));
110 out
= PyObject_Str(self
->args
);
118 BaseException_repr(PyBaseExceptionObject
*self
)
120 PyObject
*repr_suffix
;
125 repr_suffix
= PyObject_Repr(self
->args
);
129 name
= (char *)self
->ob_type
->tp_name
;
130 dot
= strrchr(name
, '.');
131 if (dot
!= NULL
) name
= dot
+1;
133 repr
= PyString_FromString(name
);
135 Py_DECREF(repr_suffix
);
139 PyString_ConcatAndDel(&repr
, repr_suffix
);
143 /* Pickling support */
145 BaseException_reduce(PyBaseExceptionObject
*self
)
147 if (self
->args
&& self
->dict
)
148 return PyTuple_Pack(3, self
->ob_type
, self
->args
, self
->dict
);
150 return PyTuple_Pack(2, self
->ob_type
, self
->args
);
154 * Needed for backward compatibility, since exceptions used to store
155 * all their attributes in the __dict__. Code is taken from cPickle's
156 * load_build function.
159 BaseException_setstate(PyObject
*self
, PyObject
*state
)
161 PyObject
*d_key
, *d_value
;
164 if (state
!= Py_None
) {
165 if (!PyDict_Check(state
)) {
166 PyErr_SetString(PyExc_TypeError
, "state is not a dictionary");
169 while (PyDict_Next(state
, &i
, &d_key
, &d_value
)) {
170 if (PyObject_SetAttr(self
, d_key
, d_value
) < 0)
177 #ifdef Py_USING_UNICODE
178 /* while this method generates fairly uninspired output, it a least
179 * guarantees that we can display exceptions that have unicode attributes
182 BaseException_unicode(PyBaseExceptionObject
*self
)
184 if (PyTuple_GET_SIZE(self
->args
) == 0)
185 return PyUnicode_FromUnicode(NULL
, 0);
186 if (PyTuple_GET_SIZE(self
->args
) == 1)
187 return PyObject_Unicode(PyTuple_GET_ITEM(self
->args
, 0));
188 return PyObject_Unicode(self
->args
);
190 #endif /* Py_USING_UNICODE */
192 static PyMethodDef BaseException_methods
[] = {
193 {"__reduce__", (PyCFunction
)BaseException_reduce
, METH_NOARGS
},
194 {"__setstate__", (PyCFunction
)BaseException_setstate
, METH_O
},
195 #ifdef Py_USING_UNICODE
196 {"__unicode__", (PyCFunction
)BaseException_unicode
, METH_NOARGS
},
198 {NULL
, NULL
, 0, NULL
},
204 BaseException_getitem(PyBaseExceptionObject
*self
, Py_ssize_t index
)
206 return PySequence_GetItem(self
->args
, index
);
209 static PySequenceMethods BaseException_as_sequence
= {
213 (ssizeargfunc
)BaseException_getitem
, /* sq_item; */
215 0, /* sq_ass_item; */
216 0, /* sq_ass_slice; */
217 0, /* sq_contains; */
218 0, /* sq_inplace_concat; */
219 0 /* sq_inplace_repeat; */
222 static PyMemberDef BaseException_members
[] = {
223 {"message", T_OBJECT
, offsetof(PyBaseExceptionObject
, message
), 0,
224 PyDoc_STR("exception message")},
225 {NULL
} /* Sentinel */
230 BaseException_get_dict(PyBaseExceptionObject
*self
)
232 if (self
->dict
== NULL
) {
233 self
->dict
= PyDict_New();
237 Py_INCREF(self
->dict
);
242 BaseException_set_dict(PyBaseExceptionObject
*self
, PyObject
*val
)
245 PyErr_SetString(PyExc_TypeError
, "__dict__ may not be deleted");
248 if (!PyDict_Check(val
)) {
249 PyErr_SetString(PyExc_TypeError
, "__dict__ must be a dictionary");
252 Py_CLEAR(self
->dict
);
259 BaseException_get_args(PyBaseExceptionObject
*self
)
261 if (self
->args
== NULL
) {
265 Py_INCREF(self
->args
);
270 BaseException_set_args(PyBaseExceptionObject
*self
, PyObject
*val
)
274 PyErr_SetString(PyExc_TypeError
, "args may not be deleted");
277 seq
= PySequence_Tuple(val
);
279 Py_CLEAR(self
->args
);
284 static PyGetSetDef BaseException_getset
[] = {
285 {"__dict__", (getter
)BaseException_get_dict
, (setter
)BaseException_set_dict
},
286 {"args", (getter
)BaseException_get_args
, (setter
)BaseException_set_args
},
291 static PyTypeObject _PyExc_BaseException
= {
292 PyObject_HEAD_INIT(NULL
)
294 EXC_MODULE_NAME
"BaseException", /*tp_name*/
295 sizeof(PyBaseExceptionObject
), /*tp_basicsize*/
297 (destructor
)BaseException_dealloc
, /*tp_dealloc*/
302 (reprfunc
)BaseException_repr
, /*tp_repr*/
304 &BaseException_as_sequence
, /*tp_as_sequence*/
308 (reprfunc
)BaseException_str
, /*tp_str*/
309 PyObject_GenericGetAttr
, /*tp_getattro*/
310 PyObject_GenericSetAttr
, /*tp_setattro*/
312 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
, /*tp_flags*/
313 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
314 (traverseproc
)BaseException_traverse
, /* tp_traverse */
315 (inquiry
)BaseException_clear
, /* tp_clear */
316 0, /* tp_richcompare */
317 0, /* tp_weaklistoffset */
320 BaseException_methods
, /* tp_methods */
321 BaseException_members
, /* tp_members */
322 BaseException_getset
, /* tp_getset */
325 0, /* tp_descr_get */
326 0, /* tp_descr_set */
327 offsetof(PyBaseExceptionObject
, dict
), /* tp_dictoffset */
328 (initproc
)BaseException_init
, /* tp_init */
330 BaseException_new
, /* tp_new */
332 /* the CPython API expects exceptions to be (PyObject *) - both a hold-over
333 from the previous implmentation and also allowing Python objects to be used
335 PyObject
*PyExc_BaseException
= (PyObject
*)&_PyExc_BaseException
;
337 /* note these macros omit the last semicolon so the macro invocation may
338 * include it and not look strange.
340 #define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
341 static PyTypeObject _PyExc_ ## EXCNAME = { \
342 PyObject_HEAD_INIT(NULL) \
344 EXC_MODULE_NAME # EXCNAME, \
345 sizeof(PyBaseExceptionObject), \
346 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
347 0, 0, 0, 0, 0, 0, 0, \
348 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
349 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
350 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
351 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
352 (initproc)BaseException_init, 0, BaseException_new,\
354 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
356 #define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
357 static PyTypeObject _PyExc_ ## EXCNAME = { \
358 PyObject_HEAD_INIT(NULL) \
360 EXC_MODULE_NAME # EXCNAME, \
361 sizeof(Py ## EXCSTORE ## Object), \
362 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
364 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
365 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
366 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
367 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
368 (initproc)EXCSTORE ## _init, 0, BaseException_new,\
370 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
372 #define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDEALLOC, EXCMETHODS, EXCMEMBERS, EXCSTR, EXCDOC) \
373 static PyTypeObject _PyExc_ ## EXCNAME = { \
374 PyObject_HEAD_INIT(NULL) \
376 EXC_MODULE_NAME # EXCNAME, \
377 sizeof(Py ## EXCSTORE ## Object), 0, \
378 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
379 (reprfunc)EXCSTR, 0, 0, 0, \
380 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
381 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
382 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
383 EXCMEMBERS, 0, &_ ## EXCBASE, \
384 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
385 (initproc)EXCSTORE ## _init, 0, BaseException_new,\
387 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
391 * Exception extends BaseException
393 SimpleExtendsException(PyExc_BaseException
, Exception
,
394 "Common base class for all non-exit exceptions.");
398 * StandardError extends Exception
400 SimpleExtendsException(PyExc_Exception
, StandardError
,
401 "Base class for all standard Python exceptions that do not represent\n"
402 "interpreter exiting.");
406 * TypeError extends StandardError
408 SimpleExtendsException(PyExc_StandardError
, TypeError
,
409 "Inappropriate argument type.");
413 * StopIteration extends Exception
415 SimpleExtendsException(PyExc_Exception
, StopIteration
,
416 "Signal the end from iterator.next().");
420 * GeneratorExit extends Exception
422 SimpleExtendsException(PyExc_Exception
, GeneratorExit
,
423 "Request that a generator exit.");
427 * SystemExit extends BaseException
431 SystemExit_init(PySystemExitObject
*self
, PyObject
*args
, PyObject
*kwds
)
433 Py_ssize_t size
= PyTuple_GET_SIZE(args
);
435 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
440 Py_CLEAR(self
->code
);
442 self
->code
= PyTuple_GET_ITEM(args
, 0);
445 Py_INCREF(self
->code
);
450 SystemExit_clear(PySystemExitObject
*self
)
452 Py_CLEAR(self
->code
);
453 return BaseException_clear((PyBaseExceptionObject
*)self
);
457 SystemExit_dealloc(PySystemExitObject
*self
)
459 SystemExit_clear(self
);
460 self
->ob_type
->tp_free((PyObject
*)self
);
464 SystemExit_traverse(PySystemExitObject
*self
, visitproc visit
, void *arg
)
466 Py_VISIT(self
->code
);
467 return BaseException_traverse((PyBaseExceptionObject
*)self
, visit
, arg
);
470 static PyMemberDef SystemExit_members
[] = {
471 {"message", T_OBJECT
, offsetof(PySystemExitObject
, message
), 0,
472 PyDoc_STR("exception message")},
473 {"code", T_OBJECT
, offsetof(PySystemExitObject
, code
), 0,
474 PyDoc_STR("exception code")},
475 {NULL
} /* Sentinel */
478 ComplexExtendsException(PyExc_BaseException
, SystemExit
, SystemExit
,
479 SystemExit_dealloc
, 0, SystemExit_members
, 0,
480 "Request to exit from the interpreter.");
483 * KeyboardInterrupt extends BaseException
485 SimpleExtendsException(PyExc_BaseException
, KeyboardInterrupt
,
486 "Program interrupted by user.");
490 * ImportError extends StandardError
492 SimpleExtendsException(PyExc_StandardError
, ImportError
,
493 "Import can't find module, or can't find name in module.");
497 * EnvironmentError extends StandardError
500 /* Where a function has a single filename, such as open() or some
501 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
502 * called, giving a third argument which is the filename. But, so
503 * that old code using in-place unpacking doesn't break, e.g.:
505 * except IOError, (errno, strerror):
507 * we hack args so that it only contains two items. This also
508 * means we need our own __str__() which prints out the filename
509 * when it was supplied.
512 EnvironmentError_init(PyEnvironmentErrorObject
*self
, PyObject
*args
,
515 PyObject
*myerrno
= NULL
, *strerror
= NULL
, *filename
= NULL
;
516 PyObject
*subslice
= NULL
;
518 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
521 if (PyTuple_GET_SIZE(args
) <= 1) {
525 if (!PyArg_UnpackTuple(args
, "EnvironmentError", 2, 3,
526 &myerrno
, &strerror
, &filename
)) {
529 Py_CLEAR(self
->myerrno
); /* replacing */
530 self
->myerrno
= myerrno
;
531 Py_INCREF(self
->myerrno
);
533 Py_CLEAR(self
->strerror
); /* replacing */
534 self
->strerror
= strerror
;
535 Py_INCREF(self
->strerror
);
537 /* self->filename will remain Py_None otherwise */
538 if (filename
!= NULL
) {
539 Py_CLEAR(self
->filename
); /* replacing */
540 self
->filename
= filename
;
541 Py_INCREF(self
->filename
);
543 subslice
= PyTuple_GetSlice(args
, 0, 2);
547 Py_DECREF(self
->args
); /* replacing args */
548 self
->args
= subslice
;
554 EnvironmentError_clear(PyEnvironmentErrorObject
*self
)
556 Py_CLEAR(self
->myerrno
);
557 Py_CLEAR(self
->strerror
);
558 Py_CLEAR(self
->filename
);
559 return BaseException_clear((PyBaseExceptionObject
*)self
);
563 EnvironmentError_dealloc(PyEnvironmentErrorObject
*self
)
565 EnvironmentError_clear(self
);
566 self
->ob_type
->tp_free((PyObject
*)self
);
570 EnvironmentError_traverse(PyEnvironmentErrorObject
*self
, visitproc visit
,
573 Py_VISIT(self
->myerrno
);
574 Py_VISIT(self
->strerror
);
575 Py_VISIT(self
->filename
);
576 return BaseException_traverse((PyBaseExceptionObject
*)self
, visit
, arg
);
580 EnvironmentError_str(PyEnvironmentErrorObject
*self
)
582 PyObject
*rtnval
= NULL
;
584 if (self
->filename
) {
589 fmt
= PyString_FromString("[Errno %s] %s: %s");
593 repr
= PyObject_Repr(self
->filename
);
598 tuple
= PyTuple_New(3);
606 Py_INCREF(self
->myerrno
);
607 PyTuple_SET_ITEM(tuple
, 0, self
->myerrno
);
611 PyTuple_SET_ITEM(tuple
, 0, Py_None
);
613 if (self
->strerror
) {
614 Py_INCREF(self
->strerror
);
615 PyTuple_SET_ITEM(tuple
, 1, self
->strerror
);
619 PyTuple_SET_ITEM(tuple
, 1, Py_None
);
622 PyTuple_SET_ITEM(tuple
, 2, repr
);
624 rtnval
= PyString_Format(fmt
, tuple
);
629 else if (self
->myerrno
&& self
->strerror
) {
633 fmt
= PyString_FromString("[Errno %s] %s");
637 tuple
= PyTuple_New(2);
644 Py_INCREF(self
->myerrno
);
645 PyTuple_SET_ITEM(tuple
, 0, self
->myerrno
);
649 PyTuple_SET_ITEM(tuple
, 0, Py_None
);
651 if (self
->strerror
) {
652 Py_INCREF(self
->strerror
);
653 PyTuple_SET_ITEM(tuple
, 1, self
->strerror
);
657 PyTuple_SET_ITEM(tuple
, 1, Py_None
);
660 rtnval
= PyString_Format(fmt
, tuple
);
666 rtnval
= BaseException_str((PyBaseExceptionObject
*)self
);
671 static PyMemberDef EnvironmentError_members
[] = {
672 {"message", T_OBJECT
, offsetof(PyEnvironmentErrorObject
, message
), 0,
673 PyDoc_STR("exception message")},
674 {"errno", T_OBJECT
, offsetof(PyEnvironmentErrorObject
, myerrno
), 0,
675 PyDoc_STR("exception errno")},
676 {"strerror", T_OBJECT
, offsetof(PyEnvironmentErrorObject
, strerror
), 0,
677 PyDoc_STR("exception strerror")},
678 {"filename", T_OBJECT
, offsetof(PyEnvironmentErrorObject
, filename
), 0,
679 PyDoc_STR("exception filename")},
680 {NULL
} /* Sentinel */
685 EnvironmentError_reduce(PyEnvironmentErrorObject
*self
)
687 PyObject
*args
= self
->args
;
688 PyObject
*res
= NULL
, *tmp
;
690 /* self->args is only the first two real arguments if there was a
691 * file name given to EnvironmentError. */
692 if (PyTuple_GET_SIZE(args
) == 2 && self
->filename
) {
693 args
= PyTuple_New(3);
694 if (!args
) return NULL
;
696 tmp
= PyTuple_GET_ITEM(self
->args
, 0);
698 PyTuple_SET_ITEM(args
, 0, tmp
);
700 tmp
= PyTuple_GET_ITEM(self
->args
, 1);
702 PyTuple_SET_ITEM(args
, 1, tmp
);
704 Py_INCREF(self
->filename
);
705 PyTuple_SET_ITEM(args
, 2, self
->filename
);
710 res
= PyTuple_Pack(3, self
->ob_type
, args
, self
->dict
);
712 res
= PyTuple_Pack(2, self
->ob_type
, args
);
718 static PyMethodDef EnvironmentError_methods
[] = {
719 {"__reduce__", (PyCFunction
)EnvironmentError_reduce
, METH_NOARGS
},
723 ComplexExtendsException(PyExc_StandardError
, EnvironmentError
,
724 EnvironmentError
, EnvironmentError_dealloc
,
725 EnvironmentError_methods
, EnvironmentError_members
,
726 EnvironmentError_str
,
727 "Base class for I/O related errors.");
731 * IOError extends EnvironmentError
733 MiddlingExtendsException(PyExc_EnvironmentError
, IOError
,
734 EnvironmentError
, "I/O operation failed.");
738 * OSError extends EnvironmentError
740 MiddlingExtendsException(PyExc_EnvironmentError
, OSError
,
741 EnvironmentError
, "OS system call failed.");
745 * WindowsError extends OSError
751 WindowsError_clear(PyWindowsErrorObject
*self
)
753 Py_CLEAR(self
->myerrno
);
754 Py_CLEAR(self
->strerror
);
755 Py_CLEAR(self
->filename
);
756 Py_CLEAR(self
->winerror
);
757 return BaseException_clear((PyBaseExceptionObject
*)self
);
761 WindowsError_dealloc(PyWindowsErrorObject
*self
)
763 WindowsError_clear(self
);
764 self
->ob_type
->tp_free((PyObject
*)self
);
768 WindowsError_traverse(PyWindowsErrorObject
*self
, visitproc visit
, void *arg
)
770 Py_VISIT(self
->myerrno
);
771 Py_VISIT(self
->strerror
);
772 Py_VISIT(self
->filename
);
773 Py_VISIT(self
->winerror
);
774 return BaseException_traverse((PyBaseExceptionObject
*)self
, visit
, arg
);
778 WindowsError_init(PyWindowsErrorObject
*self
, PyObject
*args
, PyObject
*kwds
)
780 PyObject
*o_errcode
= NULL
;
784 if (EnvironmentError_init((PyEnvironmentErrorObject
*)self
, args
, kwds
)
788 if (self
->myerrno
== NULL
)
791 /* Set errno to the POSIX errno, and winerror to the Win32
793 errcode
= PyInt_AsLong(self
->myerrno
);
794 if (errcode
== -1 && PyErr_Occurred())
796 posix_errno
= winerror_to_errno(errcode
);
798 Py_CLEAR(self
->winerror
);
799 self
->winerror
= self
->myerrno
;
801 o_errcode
= PyInt_FromLong(posix_errno
);
805 self
->myerrno
= o_errcode
;
812 WindowsError_str(PyWindowsErrorObject
*self
)
814 PyObject
*rtnval
= NULL
;
816 if (self
->filename
) {
821 fmt
= PyString_FromString("[Error %s] %s: %s");
825 repr
= PyObject_Repr(self
->filename
);
830 tuple
= PyTuple_New(3);
838 Py_INCREF(self
->myerrno
);
839 PyTuple_SET_ITEM(tuple
, 0, self
->myerrno
);
843 PyTuple_SET_ITEM(tuple
, 0, Py_None
);
845 if (self
->strerror
) {
846 Py_INCREF(self
->strerror
);
847 PyTuple_SET_ITEM(tuple
, 1, self
->strerror
);
851 PyTuple_SET_ITEM(tuple
, 1, Py_None
);
854 PyTuple_SET_ITEM(tuple
, 2, repr
);
856 rtnval
= PyString_Format(fmt
, tuple
);
861 else if (self
->myerrno
&& self
->strerror
) {
865 fmt
= PyString_FromString("[Error %s] %s");
869 tuple
= PyTuple_New(2);
876 Py_INCREF(self
->myerrno
);
877 PyTuple_SET_ITEM(tuple
, 0, self
->myerrno
);
881 PyTuple_SET_ITEM(tuple
, 0, Py_None
);
883 if (self
->strerror
) {
884 Py_INCREF(self
->strerror
);
885 PyTuple_SET_ITEM(tuple
, 1, self
->strerror
);
889 PyTuple_SET_ITEM(tuple
, 1, Py_None
);
892 rtnval
= PyString_Format(fmt
, tuple
);
898 rtnval
= EnvironmentError_str((PyEnvironmentErrorObject
*)self
);
903 static PyMemberDef WindowsError_members
[] = {
904 {"message", T_OBJECT
, offsetof(PyWindowsErrorObject
, message
), 0,
905 PyDoc_STR("exception message")},
906 {"errno", T_OBJECT
, offsetof(PyWindowsErrorObject
, myerrno
), 0,
907 PyDoc_STR("POSIX exception code")},
908 {"strerror", T_OBJECT
, offsetof(PyWindowsErrorObject
, strerror
), 0,
909 PyDoc_STR("exception strerror")},
910 {"filename", T_OBJECT
, offsetof(PyWindowsErrorObject
, filename
), 0,
911 PyDoc_STR("exception filename")},
912 {"winerror", T_OBJECT
, offsetof(PyWindowsErrorObject
, winerror
), 0,
913 PyDoc_STR("Win32 exception code")},
914 {NULL
} /* Sentinel */
917 ComplexExtendsException(PyExc_OSError
, WindowsError
, WindowsError
,
918 WindowsError_dealloc
, 0, WindowsError_members
,
919 WindowsError_str
, "MS-Windows OS system call failed.");
921 #endif /* MS_WINDOWS */
925 * VMSError extends OSError (I think)
928 MiddlingExtendsException(PyExc_OSError
, VMSError
, EnvironmentError
,
929 "OpenVMS OS system call failed.");
934 * EOFError extends StandardError
936 SimpleExtendsException(PyExc_StandardError
, EOFError
,
937 "Read beyond end of file.");
941 * RuntimeError extends StandardError
943 SimpleExtendsException(PyExc_StandardError
, RuntimeError
,
944 "Unspecified run-time error.");
948 * NotImplementedError extends RuntimeError
950 SimpleExtendsException(PyExc_RuntimeError
, NotImplementedError
,
951 "Method or function hasn't been implemented yet.");
954 * NameError extends StandardError
956 SimpleExtendsException(PyExc_StandardError
, NameError
,
957 "Name not found globally.");
960 * UnboundLocalError extends NameError
962 SimpleExtendsException(PyExc_NameError
, UnboundLocalError
,
963 "Local name referenced but not bound to a value.");
966 * AttributeError extends StandardError
968 SimpleExtendsException(PyExc_StandardError
, AttributeError
,
969 "Attribute not found.");
973 * SyntaxError extends StandardError
977 SyntaxError_init(PySyntaxErrorObject
*self
, PyObject
*args
, PyObject
*kwds
)
979 PyObject
*info
= NULL
;
980 Py_ssize_t lenargs
= PyTuple_GET_SIZE(args
);
982 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
987 self
->msg
= PyTuple_GET_ITEM(args
, 0);
988 Py_INCREF(self
->msg
);
991 info
= PyTuple_GET_ITEM(args
, 1);
992 info
= PySequence_Tuple(info
);
993 if (!info
) return -1;
995 if (PyTuple_GET_SIZE(info
) != 4) {
996 /* not a very good error message, but it's what Python 2.4 gives */
997 PyErr_SetString(PyExc_IndexError
, "tuple index out of range");
1002 Py_CLEAR(self
->filename
);
1003 self
->filename
= PyTuple_GET_ITEM(info
, 0);
1004 Py_INCREF(self
->filename
);
1006 Py_CLEAR(self
->lineno
);
1007 self
->lineno
= PyTuple_GET_ITEM(info
, 1);
1008 Py_INCREF(self
->lineno
);
1010 Py_CLEAR(self
->offset
);
1011 self
->offset
= PyTuple_GET_ITEM(info
, 2);
1012 Py_INCREF(self
->offset
);
1014 Py_CLEAR(self
->text
);
1015 self
->text
= PyTuple_GET_ITEM(info
, 3);
1016 Py_INCREF(self
->text
);
1024 SyntaxError_clear(PySyntaxErrorObject
*self
)
1026 Py_CLEAR(self
->msg
);
1027 Py_CLEAR(self
->filename
);
1028 Py_CLEAR(self
->lineno
);
1029 Py_CLEAR(self
->offset
);
1030 Py_CLEAR(self
->text
);
1031 Py_CLEAR(self
->print_file_and_line
);
1032 return BaseException_clear((PyBaseExceptionObject
*)self
);
1036 SyntaxError_dealloc(PySyntaxErrorObject
*self
)
1038 SyntaxError_clear(self
);
1039 self
->ob_type
->tp_free((PyObject
*)self
);
1043 SyntaxError_traverse(PySyntaxErrorObject
*self
, visitproc visit
, void *arg
)
1045 Py_VISIT(self
->msg
);
1046 Py_VISIT(self
->filename
);
1047 Py_VISIT(self
->lineno
);
1048 Py_VISIT(self
->offset
);
1049 Py_VISIT(self
->text
);
1050 Py_VISIT(self
->print_file_and_line
);
1051 return BaseException_traverse((PyBaseExceptionObject
*)self
, visit
, arg
);
1054 /* This is called "my_basename" instead of just "basename" to avoid name
1055 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1056 defined, and Python does define that. */
1058 my_basename(char *name
)
1061 char *result
= name
;
1065 while (*cp
!= '\0') {
1075 SyntaxError_str(PySyntaxErrorObject
*self
)
1079 int have_filename
= 0;
1080 int have_lineno
= 0;
1081 char *buffer
= NULL
;
1085 str
= PyObject_Str(self
->msg
);
1087 str
= PyObject_Str(Py_None
);
1088 if (!str
) return NULL
;
1089 /* Don't fiddle with non-string return (shouldn't happen anyway) */
1090 if (!PyString_Check(str
)) return str
;
1092 /* XXX -- do all the additional formatting with filename and
1095 have_filename
= (self
->filename
!= NULL
) &&
1096 PyString_Check(self
->filename
);
1097 have_lineno
= (self
->lineno
!= NULL
) && PyInt_Check(self
->lineno
);
1099 if (!have_filename
&& !have_lineno
)
1102 bufsize
= PyString_GET_SIZE(str
) + 64;
1104 bufsize
+= PyString_GET_SIZE(self
->filename
);
1106 buffer
= PyMem_MALLOC(bufsize
);
1110 if (have_filename
&& have_lineno
)
1111 PyOS_snprintf(buffer
, bufsize
, "%s (%s, line %ld)",
1112 PyString_AS_STRING(str
),
1113 my_basename(PyString_AS_STRING(self
->filename
)),
1114 PyInt_AsLong(self
->lineno
));
1115 else if (have_filename
)
1116 PyOS_snprintf(buffer
, bufsize
, "%s (%s)",
1117 PyString_AS_STRING(str
),
1118 my_basename(PyString_AS_STRING(self
->filename
)));
1119 else /* only have_lineno */
1120 PyOS_snprintf(buffer
, bufsize
, "%s (line %ld)",
1121 PyString_AS_STRING(str
),
1122 PyInt_AsLong(self
->lineno
));
1124 result
= PyString_FromString(buffer
);
1134 static PyMemberDef SyntaxError_members
[] = {
1135 {"message", T_OBJECT
, offsetof(PySyntaxErrorObject
, message
), 0,
1136 PyDoc_STR("exception message")},
1137 {"msg", T_OBJECT
, offsetof(PySyntaxErrorObject
, msg
), 0,
1138 PyDoc_STR("exception msg")},
1139 {"filename", T_OBJECT
, offsetof(PySyntaxErrorObject
, filename
), 0,
1140 PyDoc_STR("exception filename")},
1141 {"lineno", T_OBJECT
, offsetof(PySyntaxErrorObject
, lineno
), 0,
1142 PyDoc_STR("exception lineno")},
1143 {"offset", T_OBJECT
, offsetof(PySyntaxErrorObject
, offset
), 0,
1144 PyDoc_STR("exception offset")},
1145 {"text", T_OBJECT
, offsetof(PySyntaxErrorObject
, text
), 0,
1146 PyDoc_STR("exception text")},
1147 {"print_file_and_line", T_OBJECT
,
1148 offsetof(PySyntaxErrorObject
, print_file_and_line
), 0,
1149 PyDoc_STR("exception print_file_and_line")},
1150 {NULL
} /* Sentinel */
1153 ComplexExtendsException(PyExc_StandardError
, SyntaxError
, SyntaxError
,
1154 SyntaxError_dealloc
, 0, SyntaxError_members
,
1155 SyntaxError_str
, "Invalid syntax.");
1159 * IndentationError extends SyntaxError
1161 MiddlingExtendsException(PyExc_SyntaxError
, IndentationError
, SyntaxError
,
1162 "Improper indentation.");
1166 * TabError extends IndentationError
1168 MiddlingExtendsException(PyExc_IndentationError
, TabError
, SyntaxError
,
1169 "Improper mixture of spaces and tabs.");
1173 * LookupError extends StandardError
1175 SimpleExtendsException(PyExc_StandardError
, LookupError
,
1176 "Base class for lookup errors.");
1180 * IndexError extends LookupError
1182 SimpleExtendsException(PyExc_LookupError
, IndexError
,
1183 "Sequence index out of range.");
1187 * KeyError extends LookupError
1190 KeyError_str(PyBaseExceptionObject
*self
)
1192 /* If args is a tuple of exactly one item, apply repr to args[0].
1193 This is done so that e.g. the exception raised by {}[''] prints
1195 rather than the confusing
1197 alone. The downside is that if KeyError is raised with an explanatory
1198 string, that string will be displayed in quotes. Too bad.
1199 If args is anything else, use the default BaseException__str__().
1201 if (PyTuple_GET_SIZE(self
->args
) == 1) {
1202 return PyObject_Repr(PyTuple_GET_ITEM(self
->args
, 0));
1204 return BaseException_str(self
);
1207 ComplexExtendsException(PyExc_LookupError
, KeyError
, BaseException
,
1208 0, 0, 0, KeyError_str
, "Mapping key not found.");
1212 * ValueError extends StandardError
1214 SimpleExtendsException(PyExc_StandardError
, ValueError
,
1215 "Inappropriate argument value (of correct type).");
1218 * UnicodeError extends ValueError
1221 SimpleExtendsException(PyExc_ValueError
, UnicodeError
,
1222 "Unicode related error.");
1224 #ifdef Py_USING_UNICODE
1226 get_int(PyObject
*attr
, Py_ssize_t
*value
, const char *name
)
1229 PyErr_Format(PyExc_TypeError
, "%.200s attribute not set", name
);
1233 if (PyInt_Check(attr
)) {
1234 *value
= PyInt_AS_LONG(attr
);
1235 } else if (PyLong_Check(attr
)) {
1236 *value
= _PyLong_AsSsize_t(attr
);
1237 if (*value
== -1 && PyErr_Occurred())
1240 PyErr_Format(PyExc_TypeError
, "%.200s attribute must be int", name
);
1247 set_ssize_t(PyObject
**attr
, Py_ssize_t value
)
1249 PyObject
*obj
= PyInt_FromSsize_t(value
);
1258 get_string(PyObject
*attr
, const char *name
)
1261 PyErr_Format(PyExc_TypeError
, "%.200s attribute not set", name
);
1265 if (!PyString_Check(attr
)) {
1266 PyErr_Format(PyExc_TypeError
, "%.200s attribute must be str", name
);
1275 set_string(PyObject
**attr
, const char *value
)
1277 PyObject
*obj
= PyString_FromString(value
);
1287 get_unicode(PyObject
*attr
, const char *name
)
1290 PyErr_Format(PyExc_TypeError
, "%.200s attribute not set", name
);
1294 if (!PyUnicode_Check(attr
)) {
1295 PyErr_Format(PyExc_TypeError
,
1296 "%.200s attribute must be unicode", name
);
1304 PyUnicodeEncodeError_GetEncoding(PyObject
*exc
)
1306 return get_string(((PyUnicodeErrorObject
*)exc
)->encoding
, "encoding");
1310 PyUnicodeDecodeError_GetEncoding(PyObject
*exc
)
1312 return get_string(((PyUnicodeErrorObject
*)exc
)->encoding
, "encoding");
1316 PyUnicodeEncodeError_GetObject(PyObject
*exc
)
1318 return get_unicode(((PyUnicodeErrorObject
*)exc
)->object
, "object");
1322 PyUnicodeDecodeError_GetObject(PyObject
*exc
)
1324 return get_string(((PyUnicodeErrorObject
*)exc
)->object
, "object");
1328 PyUnicodeTranslateError_GetObject(PyObject
*exc
)
1330 return get_unicode(((PyUnicodeErrorObject
*)exc
)->object
, "object");
1334 PyUnicodeEncodeError_GetStart(PyObject
*exc
, Py_ssize_t
*start
)
1336 if (!get_int(((PyUnicodeErrorObject
*)exc
)->start
, start
, "start")) {
1338 PyObject
*obj
= get_unicode(((PyUnicodeErrorObject
*)exc
)->object
,
1340 if (!obj
) return -1;
1341 size
= PyUnicode_GET_SIZE(obj
);
1343 *start
= 0; /*XXX check for values <0*/
1354 PyUnicodeDecodeError_GetStart(PyObject
*exc
, Py_ssize_t
*start
)
1356 if (!get_int(((PyUnicodeErrorObject
*)exc
)->start
, start
, "start")) {
1358 PyObject
*obj
= get_string(((PyUnicodeErrorObject
*)exc
)->object
,
1360 if (!obj
) return -1;
1361 size
= PyString_GET_SIZE(obj
);
1374 PyUnicodeTranslateError_GetStart(PyObject
*exc
, Py_ssize_t
*start
)
1376 return PyUnicodeEncodeError_GetStart(exc
, start
);
1381 PyUnicodeEncodeError_SetStart(PyObject
*exc
, Py_ssize_t start
)
1383 return set_ssize_t(&((PyUnicodeErrorObject
*)exc
)->start
, start
);
1388 PyUnicodeDecodeError_SetStart(PyObject
*exc
, Py_ssize_t start
)
1390 return set_ssize_t(&((PyUnicodeErrorObject
*)exc
)->start
, start
);
1395 PyUnicodeTranslateError_SetStart(PyObject
*exc
, Py_ssize_t start
)
1397 return set_ssize_t(&((PyUnicodeErrorObject
*)exc
)->start
, start
);
1402 PyUnicodeEncodeError_GetEnd(PyObject
*exc
, Py_ssize_t
*end
)
1404 if (!get_int(((PyUnicodeErrorObject
*)exc
)->end
, end
, "end")) {
1406 PyObject
*obj
= get_unicode(((PyUnicodeErrorObject
*)exc
)->object
,
1408 if (!obj
) return -1;
1409 size
= PyUnicode_GET_SIZE(obj
);
1422 PyUnicodeDecodeError_GetEnd(PyObject
*exc
, Py_ssize_t
*end
)
1424 if (!get_int(((PyUnicodeErrorObject
*)exc
)->end
, end
, "end")) {
1426 PyObject
*obj
= get_string(((PyUnicodeErrorObject
*)exc
)->object
,
1428 if (!obj
) return -1;
1429 size
= PyString_GET_SIZE(obj
);
1442 PyUnicodeTranslateError_GetEnd(PyObject
*exc
, Py_ssize_t
*start
)
1444 return PyUnicodeEncodeError_GetEnd(exc
, start
);
1449 PyUnicodeEncodeError_SetEnd(PyObject
*exc
, Py_ssize_t end
)
1451 return set_ssize_t(&((PyUnicodeErrorObject
*)exc
)->end
, end
);
1456 PyUnicodeDecodeError_SetEnd(PyObject
*exc
, Py_ssize_t end
)
1458 return set_ssize_t(&((PyUnicodeErrorObject
*)exc
)->end
, end
);
1463 PyUnicodeTranslateError_SetEnd(PyObject
*exc
, Py_ssize_t end
)
1465 return set_ssize_t(&((PyUnicodeErrorObject
*)exc
)->end
, end
);
1469 PyUnicodeEncodeError_GetReason(PyObject
*exc
)
1471 return get_string(((PyUnicodeErrorObject
*)exc
)->reason
, "reason");
1476 PyUnicodeDecodeError_GetReason(PyObject
*exc
)
1478 return get_string(((PyUnicodeErrorObject
*)exc
)->reason
, "reason");
1483 PyUnicodeTranslateError_GetReason(PyObject
*exc
)
1485 return get_string(((PyUnicodeErrorObject
*)exc
)->reason
, "reason");
1490 PyUnicodeEncodeError_SetReason(PyObject
*exc
, const char *reason
)
1492 return set_string(&((PyUnicodeErrorObject
*)exc
)->reason
, reason
);
1497 PyUnicodeDecodeError_SetReason(PyObject
*exc
, const char *reason
)
1499 return set_string(&((PyUnicodeErrorObject
*)exc
)->reason
, reason
);
1504 PyUnicodeTranslateError_SetReason(PyObject
*exc
, const char *reason
)
1506 return set_string(&((PyUnicodeErrorObject
*)exc
)->reason
, reason
);
1511 UnicodeError_init(PyUnicodeErrorObject
*self
, PyObject
*args
, PyObject
*kwds
,
1512 PyTypeObject
*objecttype
)
1514 Py_CLEAR(self
->encoding
);
1515 Py_CLEAR(self
->object
);
1516 Py_CLEAR(self
->start
);
1517 Py_CLEAR(self
->end
);
1518 Py_CLEAR(self
->reason
);
1520 if (!PyArg_ParseTuple(args
, "O!O!O!O!O!",
1521 &PyString_Type
, &self
->encoding
,
1522 objecttype
, &self
->object
,
1523 &PyInt_Type
, &self
->start
,
1524 &PyInt_Type
, &self
->end
,
1525 &PyString_Type
, &self
->reason
)) {
1526 self
->encoding
= self
->object
= self
->start
= self
->end
=
1527 self
->reason
= NULL
;
1531 Py_INCREF(self
->encoding
);
1532 Py_INCREF(self
->object
);
1533 Py_INCREF(self
->start
);
1534 Py_INCREF(self
->end
);
1535 Py_INCREF(self
->reason
);
1541 UnicodeError_clear(PyUnicodeErrorObject
*self
)
1543 Py_CLEAR(self
->encoding
);
1544 Py_CLEAR(self
->object
);
1545 Py_CLEAR(self
->start
);
1546 Py_CLEAR(self
->end
);
1547 Py_CLEAR(self
->reason
);
1548 return BaseException_clear((PyBaseExceptionObject
*)self
);
1552 UnicodeError_dealloc(PyUnicodeErrorObject
*self
)
1554 UnicodeError_clear(self
);
1555 self
->ob_type
->tp_free((PyObject
*)self
);
1559 UnicodeError_traverse(PyUnicodeErrorObject
*self
, visitproc visit
, void *arg
)
1561 Py_VISIT(self
->encoding
);
1562 Py_VISIT(self
->object
);
1563 Py_VISIT(self
->start
);
1564 Py_VISIT(self
->end
);
1565 Py_VISIT(self
->reason
);
1566 return BaseException_traverse((PyBaseExceptionObject
*)self
, visit
, arg
);
1569 static PyMemberDef UnicodeError_members
[] = {
1570 {"message", T_OBJECT
, offsetof(PyUnicodeErrorObject
, message
), 0,
1571 PyDoc_STR("exception message")},
1572 {"encoding", T_OBJECT
, offsetof(PyUnicodeErrorObject
, encoding
), 0,
1573 PyDoc_STR("exception encoding")},
1574 {"object", T_OBJECT
, offsetof(PyUnicodeErrorObject
, object
), 0,
1575 PyDoc_STR("exception object")},
1576 {"start", T_OBJECT
, offsetof(PyUnicodeErrorObject
, start
), 0,
1577 PyDoc_STR("exception start")},
1578 {"end", T_OBJECT
, offsetof(PyUnicodeErrorObject
, end
), 0,
1579 PyDoc_STR("exception end")},
1580 {"reason", T_OBJECT
, offsetof(PyUnicodeErrorObject
, reason
), 0,
1581 PyDoc_STR("exception reason")},
1582 {NULL
} /* Sentinel */
1587 * UnicodeEncodeError extends UnicodeError
1591 UnicodeEncodeError_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1593 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
1595 return UnicodeError_init((PyUnicodeErrorObject
*)self
, args
,
1596 kwds
, &PyUnicode_Type
);
1600 UnicodeEncodeError_str(PyObject
*self
)
1605 if (PyUnicodeEncodeError_GetStart(self
, &start
))
1608 if (PyUnicodeEncodeError_GetEnd(self
, &end
))
1612 int badchar
= (int)PyUnicode_AS_UNICODE(((PyUnicodeErrorObject
*)self
)->object
)[start
];
1613 char badchar_str
[20];
1614 if (badchar
<= 0xff)
1615 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "x%02x", badchar
);
1616 else if (badchar
<= 0xffff)
1617 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "u%04x", badchar
);
1619 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "U%08x", badchar
);
1620 return PyString_FromFormat(
1621 "'%.400s' codec can't encode character u'\\%s' in position %zd: %.400s",
1622 PyString_AS_STRING(((PyUnicodeErrorObject
*)self
)->encoding
),
1625 PyString_AS_STRING(((PyUnicodeErrorObject
*)self
)->reason
)
1628 return PyString_FromFormat(
1629 "'%.400s' codec can't encode characters in position %zd-%zd: %.400s",
1630 PyString_AS_STRING(((PyUnicodeErrorObject
*)self
)->encoding
),
1633 PyString_AS_STRING(((PyUnicodeErrorObject
*)self
)->reason
)
1637 static PyTypeObject _PyExc_UnicodeEncodeError
= {
1638 PyObject_HEAD_INIT(NULL
)
1640 "UnicodeEncodeError",
1641 sizeof(PyUnicodeErrorObject
), 0,
1642 (destructor
)UnicodeError_dealloc
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1643 (reprfunc
)UnicodeEncodeError_str
, 0, 0, 0,
1644 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
1645 PyDoc_STR("Unicode encoding error."), (traverseproc
)UnicodeError_traverse
,
1646 (inquiry
)UnicodeError_clear
, 0, 0, 0, 0, 0, UnicodeError_members
,
1647 0, &_PyExc_UnicodeError
, 0, 0, 0, offsetof(PyUnicodeErrorObject
, dict
),
1648 (initproc
)UnicodeEncodeError_init
, 0, BaseException_new
,
1650 PyObject
*PyExc_UnicodeEncodeError
= (PyObject
*)&_PyExc_UnicodeEncodeError
;
1653 PyUnicodeEncodeError_Create(
1654 const char *encoding
, const Py_UNICODE
*object
, Py_ssize_t length
,
1655 Py_ssize_t start
, Py_ssize_t end
, const char *reason
)
1657 return PyObject_CallFunction(PyExc_UnicodeEncodeError
, "su#nns",
1658 encoding
, object
, length
, start
, end
, reason
);
1663 * UnicodeDecodeError extends UnicodeError
1667 UnicodeDecodeError_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1669 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
1671 return UnicodeError_init((PyUnicodeErrorObject
*)self
, args
,
1672 kwds
, &PyString_Type
);
1676 UnicodeDecodeError_str(PyObject
*self
)
1678 Py_ssize_t start
= 0;
1681 if (PyUnicodeDecodeError_GetStart(self
, &start
))
1684 if (PyUnicodeDecodeError_GetEnd(self
, &end
))
1688 /* FromFormat does not support %02x, so format that separately */
1690 PyOS_snprintf(byte
, sizeof(byte
), "%02x",
1691 ((int)PyString_AS_STRING(((PyUnicodeErrorObject
*)self
)->object
)[start
])&0xff);
1692 return PyString_FromFormat(
1693 "'%.400s' codec can't decode byte 0x%s in position %zd: %.400s",
1694 PyString_AS_STRING(((PyUnicodeErrorObject
*)self
)->encoding
),
1697 PyString_AS_STRING(((PyUnicodeErrorObject
*)self
)->reason
)
1700 return PyString_FromFormat(
1701 "'%.400s' codec can't decode bytes in position %zd-%zd: %.400s",
1702 PyString_AS_STRING(((PyUnicodeErrorObject
*)self
)->encoding
),
1705 PyString_AS_STRING(((PyUnicodeErrorObject
*)self
)->reason
)
1709 static PyTypeObject _PyExc_UnicodeDecodeError
= {
1710 PyObject_HEAD_INIT(NULL
)
1712 EXC_MODULE_NAME
"UnicodeDecodeError",
1713 sizeof(PyUnicodeErrorObject
), 0,
1714 (destructor
)UnicodeError_dealloc
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1715 (reprfunc
)UnicodeDecodeError_str
, 0, 0, 0,
1716 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
1717 PyDoc_STR("Unicode decoding error."), (traverseproc
)UnicodeError_traverse
,
1718 (inquiry
)UnicodeError_clear
, 0, 0, 0, 0, 0, UnicodeError_members
,
1719 0, &_PyExc_UnicodeError
, 0, 0, 0, offsetof(PyUnicodeErrorObject
, dict
),
1720 (initproc
)UnicodeDecodeError_init
, 0, BaseException_new
,
1722 PyObject
*PyExc_UnicodeDecodeError
= (PyObject
*)&_PyExc_UnicodeDecodeError
;
1725 PyUnicodeDecodeError_Create(
1726 const char *encoding
, const char *object
, Py_ssize_t length
,
1727 Py_ssize_t start
, Py_ssize_t end
, const char *reason
)
1729 assert(length
< INT_MAX
);
1730 assert(start
< INT_MAX
);
1731 assert(end
< INT_MAX
);
1732 return PyObject_CallFunction(PyExc_UnicodeDecodeError
, "ss#nns",
1733 encoding
, object
, length
, start
, end
, reason
);
1738 * UnicodeTranslateError extends UnicodeError
1742 UnicodeTranslateError_init(PyUnicodeErrorObject
*self
, PyObject
*args
,
1745 if (BaseException_init((PyBaseExceptionObject
*)self
, args
, kwds
) == -1)
1748 Py_CLEAR(self
->object
);
1749 Py_CLEAR(self
->start
);
1750 Py_CLEAR(self
->end
);
1751 Py_CLEAR(self
->reason
);
1753 if (!PyArg_ParseTuple(args
, "O!O!O!O!",
1754 &PyUnicode_Type
, &self
->object
,
1755 &PyInt_Type
, &self
->start
,
1756 &PyInt_Type
, &self
->end
,
1757 &PyString_Type
, &self
->reason
)) {
1758 self
->object
= self
->start
= self
->end
= self
->reason
= NULL
;
1762 Py_INCREF(self
->object
);
1763 Py_INCREF(self
->start
);
1764 Py_INCREF(self
->end
);
1765 Py_INCREF(self
->reason
);
1772 UnicodeTranslateError_str(PyObject
*self
)
1777 if (PyUnicodeTranslateError_GetStart(self
, &start
))
1780 if (PyUnicodeTranslateError_GetEnd(self
, &end
))
1784 int badchar
= (int)PyUnicode_AS_UNICODE(((PyUnicodeErrorObject
*)self
)->object
)[start
];
1785 char badchar_str
[20];
1786 if (badchar
<= 0xff)
1787 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "x%02x", badchar
);
1788 else if (badchar
<= 0xffff)
1789 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "u%04x", badchar
);
1791 PyOS_snprintf(badchar_str
, sizeof(badchar_str
), "U%08x", badchar
);
1792 return PyString_FromFormat(
1793 "can't translate character u'\\%s' in position %zd: %.400s",
1796 PyString_AS_STRING(((PyUnicodeErrorObject
*)self
)->reason
)
1799 return PyString_FromFormat(
1800 "can't translate characters in position %zd-%zd: %.400s",
1803 PyString_AS_STRING(((PyUnicodeErrorObject
*)self
)->reason
)
1807 static PyTypeObject _PyExc_UnicodeTranslateError
= {
1808 PyObject_HEAD_INIT(NULL
)
1810 EXC_MODULE_NAME
"UnicodeTranslateError",
1811 sizeof(PyUnicodeErrorObject
), 0,
1812 (destructor
)UnicodeError_dealloc
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1813 (reprfunc
)UnicodeTranslateError_str
, 0, 0, 0,
1814 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
1815 PyDoc_STR("Unicode decoding error."), (traverseproc
)UnicodeError_traverse
,
1816 (inquiry
)UnicodeError_clear
, 0, 0, 0, 0, 0, UnicodeError_members
,
1817 0, &_PyExc_UnicodeError
, 0, 0, 0, offsetof(PyUnicodeErrorObject
, dict
),
1818 (initproc
)UnicodeTranslateError_init
, 0, BaseException_new
,
1820 PyObject
*PyExc_UnicodeTranslateError
= (PyObject
*)&_PyExc_UnicodeTranslateError
;
1823 PyUnicodeTranslateError_Create(
1824 const Py_UNICODE
*object
, Py_ssize_t length
,
1825 Py_ssize_t start
, Py_ssize_t end
, const char *reason
)
1827 return PyObject_CallFunction(PyExc_UnicodeTranslateError
, "u#nns",
1828 object
, length
, start
, end
, reason
);
1834 * AssertionError extends StandardError
1836 SimpleExtendsException(PyExc_StandardError
, AssertionError
,
1837 "Assertion failed.");
1841 * ArithmeticError extends StandardError
1843 SimpleExtendsException(PyExc_StandardError
, ArithmeticError
,
1844 "Base class for arithmetic errors.");
1848 * FloatingPointError extends ArithmeticError
1850 SimpleExtendsException(PyExc_ArithmeticError
, FloatingPointError
,
1851 "Floating point operation failed.");
1855 * OverflowError extends ArithmeticError
1857 SimpleExtendsException(PyExc_ArithmeticError
, OverflowError
,
1858 "Result too large to be represented.");
1862 * ZeroDivisionError extends ArithmeticError
1864 SimpleExtendsException(PyExc_ArithmeticError
, ZeroDivisionError
,
1865 "Second argument to a division or modulo operation was zero.");
1869 * SystemError extends StandardError
1871 SimpleExtendsException(PyExc_StandardError
, SystemError
,
1872 "Internal error in the Python interpreter.\n"
1874 "Please report this to the Python maintainer, along with the traceback,\n"
1875 "the Python version, and the hardware/OS platform and version.");
1879 * ReferenceError extends StandardError
1881 SimpleExtendsException(PyExc_StandardError
, ReferenceError
,
1882 "Weak ref proxy used after referent went away.");
1886 * MemoryError extends StandardError
1888 SimpleExtendsException(PyExc_StandardError
, MemoryError
, "Out of memory.");
1891 /* Warning category docstrings */
1894 * Warning extends Exception
1896 SimpleExtendsException(PyExc_Exception
, Warning
,
1897 "Base class for warning categories.");
1901 * UserWarning extends Warning
1903 SimpleExtendsException(PyExc_Warning
, UserWarning
,
1904 "Base class for warnings generated by user code.");
1908 * DeprecationWarning extends Warning
1910 SimpleExtendsException(PyExc_Warning
, DeprecationWarning
,
1911 "Base class for warnings about deprecated features.");
1915 * PendingDeprecationWarning extends Warning
1917 SimpleExtendsException(PyExc_Warning
, PendingDeprecationWarning
,
1918 "Base class for warnings about features which will be deprecated\n"
1923 * SyntaxWarning extends Warning
1925 SimpleExtendsException(PyExc_Warning
, SyntaxWarning
,
1926 "Base class for warnings about dubious syntax.");
1930 * RuntimeWarning extends Warning
1932 SimpleExtendsException(PyExc_Warning
, RuntimeWarning
,
1933 "Base class for warnings about dubious runtime behavior.");
1937 * FutureWarning extends Warning
1939 SimpleExtendsException(PyExc_Warning
, FutureWarning
,
1940 "Base class for warnings about constructs that will change semantically\n"
1945 * ImportWarning extends Warning
1947 SimpleExtendsException(PyExc_Warning
, ImportWarning
,
1948 "Base class for warnings about probable mistakes in module imports");
1951 /* Pre-computed MemoryError instance. Best to create this as early as
1952 * possible and not wait until a MemoryError is actually raised!
1954 PyObject
*PyExc_MemoryErrorInst
=NULL
;
1956 /* module global functions */
1957 static PyMethodDef functions
[] = {
1962 #define PRE_INIT(TYPE) if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
1963 Py_FatalError("exceptions bootstrapping error.");
1965 #define POST_INIT(TYPE) Py_INCREF(PyExc_ ## TYPE); \
1966 PyModule_AddObject(m, # TYPE, PyExc_ ## TYPE); \
1967 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
1968 Py_FatalError("Module dictionary insertion problem.");
1970 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
1971 /* crt variable checking in VisualStudio .NET 2005 */
1974 static int prevCrtReportMode
;
1975 static _invalid_parameter_handler prevCrtHandler
;
1977 /* Invalid parameter handler. Sets a ValueError exception */
1979 InvalidParameterHandler(
1980 const wchar_t * expression
,
1981 const wchar_t * function
,
1982 const wchar_t * file
,
1984 uintptr_t pReserved
)
1986 /* Do nothing, allow execution to continue. Usually this
1987 * means that the CRT will set errno to EINVAL
1996 PyObject
*m
, *bltinmod
, *bdict
;
1998 PRE_INIT(BaseException
)
2000 PRE_INIT(StandardError
)
2002 PRE_INIT(StopIteration
)
2003 PRE_INIT(GeneratorExit
)
2004 PRE_INIT(SystemExit
)
2005 PRE_INIT(KeyboardInterrupt
)
2006 PRE_INIT(ImportError
)
2007 PRE_INIT(EnvironmentError
)
2011 PRE_INIT(WindowsError
)
2017 PRE_INIT(RuntimeError
)
2018 PRE_INIT(NotImplementedError
)
2020 PRE_INIT(UnboundLocalError
)
2021 PRE_INIT(AttributeError
)
2022 PRE_INIT(SyntaxError
)
2023 PRE_INIT(IndentationError
)
2025 PRE_INIT(LookupError
)
2026 PRE_INIT(IndexError
)
2028 PRE_INIT(ValueError
)
2029 PRE_INIT(UnicodeError
)
2030 #ifdef Py_USING_UNICODE
2031 PRE_INIT(UnicodeEncodeError
)
2032 PRE_INIT(UnicodeDecodeError
)
2033 PRE_INIT(UnicodeTranslateError
)
2035 PRE_INIT(AssertionError
)
2036 PRE_INIT(ArithmeticError
)
2037 PRE_INIT(FloatingPointError
)
2038 PRE_INIT(OverflowError
)
2039 PRE_INIT(ZeroDivisionError
)
2040 PRE_INIT(SystemError
)
2041 PRE_INIT(ReferenceError
)
2042 PRE_INIT(MemoryError
)
2044 PRE_INIT(UserWarning
)
2045 PRE_INIT(DeprecationWarning
)
2046 PRE_INIT(PendingDeprecationWarning
)
2047 PRE_INIT(SyntaxWarning
)
2048 PRE_INIT(RuntimeWarning
)
2049 PRE_INIT(FutureWarning
)
2050 PRE_INIT(ImportWarning
)
2052 m
= Py_InitModule4("exceptions", functions
, exceptions_doc
,
2053 (PyObject
*)NULL
, PYTHON_API_VERSION
);
2054 if (m
== NULL
) return;
2056 bltinmod
= PyImport_ImportModule("__builtin__");
2057 if (bltinmod
== NULL
)
2058 Py_FatalError("exceptions bootstrapping error.");
2059 bdict
= PyModule_GetDict(bltinmod
);
2061 Py_FatalError("exceptions bootstrapping error.");
2063 POST_INIT(BaseException
)
2064 POST_INIT(Exception
)
2065 POST_INIT(StandardError
)
2066 POST_INIT(TypeError
)
2067 POST_INIT(StopIteration
)
2068 POST_INIT(GeneratorExit
)
2069 POST_INIT(SystemExit
)
2070 POST_INIT(KeyboardInterrupt
)
2071 POST_INIT(ImportError
)
2072 POST_INIT(EnvironmentError
)
2076 POST_INIT(WindowsError
)
2082 POST_INIT(RuntimeError
)
2083 POST_INIT(NotImplementedError
)
2084 POST_INIT(NameError
)
2085 POST_INIT(UnboundLocalError
)
2086 POST_INIT(AttributeError
)
2087 POST_INIT(SyntaxError
)
2088 POST_INIT(IndentationError
)
2090 POST_INIT(LookupError
)
2091 POST_INIT(IndexError
)
2093 POST_INIT(ValueError
)
2094 POST_INIT(UnicodeError
)
2095 #ifdef Py_USING_UNICODE
2096 POST_INIT(UnicodeEncodeError
)
2097 POST_INIT(UnicodeDecodeError
)
2098 POST_INIT(UnicodeTranslateError
)
2100 POST_INIT(AssertionError
)
2101 POST_INIT(ArithmeticError
)
2102 POST_INIT(FloatingPointError
)
2103 POST_INIT(OverflowError
)
2104 POST_INIT(ZeroDivisionError
)
2105 POST_INIT(SystemError
)
2106 POST_INIT(ReferenceError
)
2107 POST_INIT(MemoryError
)
2109 POST_INIT(UserWarning
)
2110 POST_INIT(DeprecationWarning
)
2111 POST_INIT(PendingDeprecationWarning
)
2112 POST_INIT(SyntaxWarning
)
2113 POST_INIT(RuntimeWarning
)
2114 POST_INIT(FutureWarning
)
2115 POST_INIT(ImportWarning
)
2117 PyExc_MemoryErrorInst
= BaseException_new(&_PyExc_MemoryError
, NULL
, NULL
);
2118 if (!PyExc_MemoryErrorInst
)
2119 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
2121 Py_DECREF(bltinmod
);
2123 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
2124 /* Set CRT argument error handler */
2125 prevCrtHandler
= _set_invalid_parameter_handler(InvalidParameterHandler
);
2126 /* turn off assertions in debug mode */
2127 prevCrtReportMode
= _CrtSetReportMode(_CRT_ASSERT
, 0);
2134 Py_XDECREF(PyExc_MemoryErrorInst
);
2135 PyExc_MemoryErrorInst
= NULL
;
2136 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
2137 /* reset CRT error handling */
2138 _set_invalid_parameter_handler(prevCrtHandler
);
2139 _CrtSetReportMode(_CRT_ASSERT
, prevCrtReportMode
);