Kill a couple of "<>"
[python.git] / Objects / exceptions.c
blobc246d67dbea2f31b685c7985e71b2693cf4445ea
1 /*
2 * New exceptions.c written in Iceland by Richard Jones and Georg Brandl.
4 * Thanks go to Tim Peters and Michael Hudson for debugging.
5 */
7 #define PY_SSIZE_T_CLEAN
8 #include <Python.h>
9 #include "structmember.h"
10 #include "osdefs.h"
12 #define EXC_MODULE_NAME "exceptions."
14 /* NOTE: If the exception class hierarchy changes, don't forget to update
15 * Lib/test/exception_hierarchy.txt
18 PyDoc_STRVAR(exceptions_doc, "Python's standard exception class hierarchy.\n\
19 \n\
20 Exceptions found here are defined both in the exceptions module and the\n\
21 built-in namespace. It is recommended that user-defined exceptions\n\
22 inherit from Exception. See the documentation for the exception\n\
23 inheritance hierarchy.\n\
24 ");
27 * BaseException
29 static PyObject *
30 BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
32 PyBaseExceptionObject *self;
34 self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
35 if (!self)
36 return NULL;
37 /* the dict is created on the fly in PyObject_GenericSetAttr */
38 self->message = self->dict = NULL;
40 self->args = PyTuple_New(0);
41 if (!self->args) {
42 Py_DECREF(self);
43 return NULL;
46 self->message = PyString_FromString("");
47 if (!self->message) {
48 Py_DECREF(self);
49 return NULL;
52 return (PyObject *)self;
55 static int
56 BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
58 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
59 return -1;
61 Py_DECREF(self->args);
62 self->args = args;
63 Py_INCREF(self->args);
65 if (PyTuple_GET_SIZE(self->args) == 1) {
66 Py_CLEAR(self->message);
67 self->message = PyTuple_GET_ITEM(self->args, 0);
68 Py_INCREF(self->message);
70 return 0;
73 static int
74 BaseException_clear(PyBaseExceptionObject *self)
76 Py_CLEAR(self->dict);
77 Py_CLEAR(self->args);
78 Py_CLEAR(self->message);
79 return 0;
82 static void
83 BaseException_dealloc(PyBaseExceptionObject *self)
85 _PyObject_GC_UNTRACK(self);
86 BaseException_clear(self);
87 Py_TYPE(self)->tp_free((PyObject *)self);
90 static int
91 BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
93 Py_VISIT(self->dict);
94 Py_VISIT(self->args);
95 Py_VISIT(self->message);
96 return 0;
99 static PyObject *
100 BaseException_str(PyBaseExceptionObject *self)
102 PyObject *out;
104 switch (PyTuple_GET_SIZE(self->args)) {
105 case 0:
106 out = PyString_FromString("");
107 break;
108 case 1:
109 out = PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
110 break;
111 default:
112 out = PyObject_Str(self->args);
113 break;
116 return out;
119 #ifdef Py_USING_UNICODE
120 static PyObject *
121 BaseException_unicode(PyBaseExceptionObject *self)
123 PyObject *out;
125 /* issue6108: if __str__ has been overridden in the subclass, unicode()
126 should return the message returned by __str__ as used to happen
127 before this method was implemented. */
128 if (Py_TYPE(self)->tp_str != (reprfunc)BaseException_str) {
129 PyObject *str;
130 /* Unlike PyObject_Str, tp_str can return unicode (i.e. return the
131 equivalent of unicode(e.__str__()) instead of unicode(str(e))). */
132 str = Py_TYPE(self)->tp_str((PyObject*)self);
133 if (str == NULL)
134 return NULL;
135 out = PyObject_Unicode(str);
136 Py_DECREF(str);
137 return out;
140 switch (PyTuple_GET_SIZE(self->args)) {
141 case 0:
142 out = PyUnicode_FromString("");
143 break;
144 case 1:
145 out = PyObject_Unicode(PyTuple_GET_ITEM(self->args, 0));
146 break;
147 default:
148 out = PyObject_Unicode(self->args);
149 break;
152 return out;
154 #endif
156 static PyObject *
157 BaseException_repr(PyBaseExceptionObject *self)
159 PyObject *repr_suffix;
160 PyObject *repr;
161 char *name;
162 char *dot;
164 repr_suffix = PyObject_Repr(self->args);
165 if (!repr_suffix)
166 return NULL;
168 name = (char *)Py_TYPE(self)->tp_name;
169 dot = strrchr(name, '.');
170 if (dot != NULL) name = dot+1;
172 repr = PyString_FromString(name);
173 if (!repr) {
174 Py_DECREF(repr_suffix);
175 return NULL;
178 PyString_ConcatAndDel(&repr, repr_suffix);
179 return repr;
182 /* Pickling support */
183 static PyObject *
184 BaseException_reduce(PyBaseExceptionObject *self)
186 if (self->args && self->dict)
187 return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
188 else
189 return PyTuple_Pack(2, Py_TYPE(self), self->args);
193 * Needed for backward compatibility, since exceptions used to store
194 * all their attributes in the __dict__. Code is taken from cPickle's
195 * load_build function.
197 static PyObject *
198 BaseException_setstate(PyObject *self, PyObject *state)
200 PyObject *d_key, *d_value;
201 Py_ssize_t i = 0;
203 if (state != Py_None) {
204 if (!PyDict_Check(state)) {
205 PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
206 return NULL;
208 while (PyDict_Next(state, &i, &d_key, &d_value)) {
209 if (PyObject_SetAttr(self, d_key, d_value) < 0)
210 return NULL;
213 Py_RETURN_NONE;
217 static PyMethodDef BaseException_methods[] = {
218 {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
219 {"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
220 #ifdef Py_USING_UNICODE
221 {"__unicode__", (PyCFunction)BaseException_unicode, METH_NOARGS },
222 #endif
223 {NULL, NULL, 0, NULL},
228 static PyObject *
229 BaseException_getitem(PyBaseExceptionObject *self, Py_ssize_t index)
231 if (PyErr_WarnPy3k("__getitem__ not supported for exception "
232 "classes in 3.x; use args attribute", 1) < 0)
233 return NULL;
234 return PySequence_GetItem(self->args, index);
237 static PyObject *
238 BaseException_getslice(PyBaseExceptionObject *self,
239 Py_ssize_t start, Py_ssize_t stop)
241 if (PyErr_WarnPy3k("__getslice__ not supported for exception "
242 "classes in 3.x; use args attribute", 1) < 0)
243 return NULL;
244 return PySequence_GetSlice(self->args, start, stop);
247 static PySequenceMethods BaseException_as_sequence = {
248 0, /* sq_length; */
249 0, /* sq_concat; */
250 0, /* sq_repeat; */
251 (ssizeargfunc)BaseException_getitem, /* sq_item; */
252 (ssizessizeargfunc)BaseException_getslice, /* sq_slice; */
253 0, /* sq_ass_item; */
254 0, /* sq_ass_slice; */
255 0, /* sq_contains; */
256 0, /* sq_inplace_concat; */
257 0 /* sq_inplace_repeat; */
260 static PyObject *
261 BaseException_get_dict(PyBaseExceptionObject *self)
263 if (self->dict == NULL) {
264 self->dict = PyDict_New();
265 if (!self->dict)
266 return NULL;
268 Py_INCREF(self->dict);
269 return self->dict;
272 static int
273 BaseException_set_dict(PyBaseExceptionObject *self, PyObject *val)
275 if (val == NULL) {
276 PyErr_SetString(PyExc_TypeError, "__dict__ may not be deleted");
277 return -1;
279 if (!PyDict_Check(val)) {
280 PyErr_SetString(PyExc_TypeError, "__dict__ must be a dictionary");
281 return -1;
283 Py_CLEAR(self->dict);
284 Py_INCREF(val);
285 self->dict = val;
286 return 0;
289 static PyObject *
290 BaseException_get_args(PyBaseExceptionObject *self)
292 if (self->args == NULL) {
293 Py_INCREF(Py_None);
294 return Py_None;
296 Py_INCREF(self->args);
297 return self->args;
300 static int
301 BaseException_set_args(PyBaseExceptionObject *self, PyObject *val)
303 PyObject *seq;
304 if (val == NULL) {
305 PyErr_SetString(PyExc_TypeError, "args may not be deleted");
306 return -1;
308 seq = PySequence_Tuple(val);
309 if (!seq) return -1;
310 Py_CLEAR(self->args);
311 self->args = seq;
312 return 0;
315 static PyObject *
316 BaseException_get_message(PyBaseExceptionObject *self)
318 PyObject *msg;
320 /* if "message" is in self->dict, accessing a user-set message attribute */
321 if (self->dict &&
322 (msg = PyDict_GetItemString(self->dict, "message"))) {
323 Py_INCREF(msg);
324 return msg;
327 if (self->message == NULL) {
328 PyErr_SetString(PyExc_AttributeError, "message attribute was deleted");
329 return NULL;
332 /* accessing the deprecated "builtin" message attribute of Exception */
333 if (PyErr_WarnEx(PyExc_DeprecationWarning,
334 "BaseException.message has been deprecated as "
335 "of Python 2.6", 1) < 0)
336 return NULL;
338 Py_INCREF(self->message);
339 return self->message;
342 static int
343 BaseException_set_message(PyBaseExceptionObject *self, PyObject *val)
345 /* if val is NULL, delete the message attribute */
346 if (val == NULL) {
347 if (self->dict && PyDict_GetItemString(self->dict, "message")) {
348 if (PyDict_DelItemString(self->dict, "message") < 0)
349 return -1;
351 Py_XDECREF(self->message);
352 self->message = NULL;
353 return 0;
356 /* else set it in __dict__, but may need to create the dict first */
357 if (self->dict == NULL) {
358 self->dict = PyDict_New();
359 if (!self->dict)
360 return -1;
362 return PyDict_SetItemString(self->dict, "message", val);
365 static PyGetSetDef BaseException_getset[] = {
366 {"__dict__", (getter)BaseException_get_dict, (setter)BaseException_set_dict},
367 {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
368 {"message", (getter)BaseException_get_message,
369 (setter)BaseException_set_message},
370 {NULL},
374 static PyTypeObject _PyExc_BaseException = {
375 PyObject_HEAD_INIT(NULL)
376 0, /*ob_size*/
377 EXC_MODULE_NAME "BaseException", /*tp_name*/
378 sizeof(PyBaseExceptionObject), /*tp_basicsize*/
379 0, /*tp_itemsize*/
380 (destructor)BaseException_dealloc, /*tp_dealloc*/
381 0, /*tp_print*/
382 0, /*tp_getattr*/
383 0, /*tp_setattr*/
384 0, /* tp_compare; */
385 (reprfunc)BaseException_repr, /*tp_repr*/
386 0, /*tp_as_number*/
387 &BaseException_as_sequence, /*tp_as_sequence*/
388 0, /*tp_as_mapping*/
389 0, /*tp_hash */
390 0, /*tp_call*/
391 (reprfunc)BaseException_str, /*tp_str*/
392 PyObject_GenericGetAttr, /*tp_getattro*/
393 PyObject_GenericSetAttr, /*tp_setattro*/
394 0, /*tp_as_buffer*/
395 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
396 Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
397 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
398 (traverseproc)BaseException_traverse, /* tp_traverse */
399 (inquiry)BaseException_clear, /* tp_clear */
400 0, /* tp_richcompare */
401 0, /* tp_weaklistoffset */
402 0, /* tp_iter */
403 0, /* tp_iternext */
404 BaseException_methods, /* tp_methods */
405 0, /* tp_members */
406 BaseException_getset, /* tp_getset */
407 0, /* tp_base */
408 0, /* tp_dict */
409 0, /* tp_descr_get */
410 0, /* tp_descr_set */
411 offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
412 (initproc)BaseException_init, /* tp_init */
413 0, /* tp_alloc */
414 BaseException_new, /* tp_new */
416 /* the CPython API expects exceptions to be (PyObject *) - both a hold-over
417 from the previous implmentation and also allowing Python objects to be used
418 in the API */
419 PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
421 /* note these macros omit the last semicolon so the macro invocation may
422 * include it and not look strange.
424 #define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
425 static PyTypeObject _PyExc_ ## EXCNAME = { \
426 PyObject_HEAD_INIT(NULL) \
427 0, \
428 EXC_MODULE_NAME # EXCNAME, \
429 sizeof(PyBaseExceptionObject), \
430 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
431 0, 0, 0, 0, 0, 0, 0, \
432 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
433 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
434 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
435 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
436 (initproc)BaseException_init, 0, BaseException_new,\
437 }; \
438 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
440 #define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
441 static PyTypeObject _PyExc_ ## EXCNAME = { \
442 PyObject_HEAD_INIT(NULL) \
443 0, \
444 EXC_MODULE_NAME # EXCNAME, \
445 sizeof(Py ## EXCSTORE ## Object), \
446 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
447 0, 0, 0, 0, 0, \
448 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
449 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
450 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
451 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
452 (initproc)EXCSTORE ## _init, 0, BaseException_new,\
453 }; \
454 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
456 #define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDEALLOC, EXCMETHODS, EXCMEMBERS, EXCSTR, EXCDOC) \
457 static PyTypeObject _PyExc_ ## EXCNAME = { \
458 PyObject_HEAD_INIT(NULL) \
459 0, \
460 EXC_MODULE_NAME # EXCNAME, \
461 sizeof(Py ## EXCSTORE ## Object), 0, \
462 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
463 (reprfunc)EXCSTR, 0, 0, 0, \
464 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
465 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
466 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
467 EXCMEMBERS, 0, &_ ## EXCBASE, \
468 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
469 (initproc)EXCSTORE ## _init, 0, BaseException_new,\
470 }; \
471 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
475 * Exception extends BaseException
477 SimpleExtendsException(PyExc_BaseException, Exception,
478 "Common base class for all non-exit exceptions.");
482 * StandardError extends Exception
484 SimpleExtendsException(PyExc_Exception, StandardError,
485 "Base class for all standard Python exceptions that do not represent\n"
486 "interpreter exiting.");
490 * TypeError extends StandardError
492 SimpleExtendsException(PyExc_StandardError, TypeError,
493 "Inappropriate argument type.");
497 * StopIteration extends Exception
499 SimpleExtendsException(PyExc_Exception, StopIteration,
500 "Signal the end from iterator.next().");
504 * GeneratorExit extends BaseException
506 SimpleExtendsException(PyExc_BaseException, GeneratorExit,
507 "Request that a generator exit.");
511 * SystemExit extends BaseException
514 static int
515 SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
517 Py_ssize_t size = PyTuple_GET_SIZE(args);
519 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
520 return -1;
522 if (size == 0)
523 return 0;
524 Py_CLEAR(self->code);
525 if (size == 1)
526 self->code = PyTuple_GET_ITEM(args, 0);
527 else if (size > 1)
528 self->code = args;
529 Py_INCREF(self->code);
530 return 0;
533 static int
534 SystemExit_clear(PySystemExitObject *self)
536 Py_CLEAR(self->code);
537 return BaseException_clear((PyBaseExceptionObject *)self);
540 static void
541 SystemExit_dealloc(PySystemExitObject *self)
543 _PyObject_GC_UNTRACK(self);
544 SystemExit_clear(self);
545 Py_TYPE(self)->tp_free((PyObject *)self);
548 static int
549 SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
551 Py_VISIT(self->code);
552 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
555 static PyMemberDef SystemExit_members[] = {
556 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
557 PyDoc_STR("exception code")},
558 {NULL} /* Sentinel */
561 ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
562 SystemExit_dealloc, 0, SystemExit_members, 0,
563 "Request to exit from the interpreter.");
566 * KeyboardInterrupt extends BaseException
568 SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
569 "Program interrupted by user.");
573 * ImportError extends StandardError
575 SimpleExtendsException(PyExc_StandardError, ImportError,
576 "Import can't find module, or can't find name in module.");
580 * EnvironmentError extends StandardError
583 /* Where a function has a single filename, such as open() or some
584 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
585 * called, giving a third argument which is the filename. But, so
586 * that old code using in-place unpacking doesn't break, e.g.:
588 * except IOError, (errno, strerror):
590 * we hack args so that it only contains two items. This also
591 * means we need our own __str__() which prints out the filename
592 * when it was supplied.
594 static int
595 EnvironmentError_init(PyEnvironmentErrorObject *self, PyObject *args,
596 PyObject *kwds)
598 PyObject *myerrno = NULL, *strerror = NULL, *filename = NULL;
599 PyObject *subslice = NULL;
601 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
602 return -1;
604 if (PyTuple_GET_SIZE(args) <= 1 || PyTuple_GET_SIZE(args) > 3) {
605 return 0;
608 if (!PyArg_UnpackTuple(args, "EnvironmentError", 2, 3,
609 &myerrno, &strerror, &filename)) {
610 return -1;
612 Py_CLEAR(self->myerrno); /* replacing */
613 self->myerrno = myerrno;
614 Py_INCREF(self->myerrno);
616 Py_CLEAR(self->strerror); /* replacing */
617 self->strerror = strerror;
618 Py_INCREF(self->strerror);
620 /* self->filename will remain Py_None otherwise */
621 if (filename != NULL) {
622 Py_CLEAR(self->filename); /* replacing */
623 self->filename = filename;
624 Py_INCREF(self->filename);
626 subslice = PyTuple_GetSlice(args, 0, 2);
627 if (!subslice)
628 return -1;
630 Py_DECREF(self->args); /* replacing args */
631 self->args = subslice;
633 return 0;
636 static int
637 EnvironmentError_clear(PyEnvironmentErrorObject *self)
639 Py_CLEAR(self->myerrno);
640 Py_CLEAR(self->strerror);
641 Py_CLEAR(self->filename);
642 return BaseException_clear((PyBaseExceptionObject *)self);
645 static void
646 EnvironmentError_dealloc(PyEnvironmentErrorObject *self)
648 _PyObject_GC_UNTRACK(self);
649 EnvironmentError_clear(self);
650 Py_TYPE(self)->tp_free((PyObject *)self);
653 static int
654 EnvironmentError_traverse(PyEnvironmentErrorObject *self, visitproc visit,
655 void *arg)
657 Py_VISIT(self->myerrno);
658 Py_VISIT(self->strerror);
659 Py_VISIT(self->filename);
660 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
663 static PyObject *
664 EnvironmentError_str(PyEnvironmentErrorObject *self)
666 PyObject *rtnval = NULL;
668 if (self->filename) {
669 PyObject *fmt;
670 PyObject *repr;
671 PyObject *tuple;
673 fmt = PyString_FromString("[Errno %s] %s: %s");
674 if (!fmt)
675 return NULL;
677 repr = PyObject_Repr(self->filename);
678 if (!repr) {
679 Py_DECREF(fmt);
680 return NULL;
682 tuple = PyTuple_New(3);
683 if (!tuple) {
684 Py_DECREF(repr);
685 Py_DECREF(fmt);
686 return NULL;
689 if (self->myerrno) {
690 Py_INCREF(self->myerrno);
691 PyTuple_SET_ITEM(tuple, 0, self->myerrno);
693 else {
694 Py_INCREF(Py_None);
695 PyTuple_SET_ITEM(tuple, 0, Py_None);
697 if (self->strerror) {
698 Py_INCREF(self->strerror);
699 PyTuple_SET_ITEM(tuple, 1, self->strerror);
701 else {
702 Py_INCREF(Py_None);
703 PyTuple_SET_ITEM(tuple, 1, Py_None);
706 PyTuple_SET_ITEM(tuple, 2, repr);
708 rtnval = PyString_Format(fmt, tuple);
710 Py_DECREF(fmt);
711 Py_DECREF(tuple);
713 else if (self->myerrno && self->strerror) {
714 PyObject *fmt;
715 PyObject *tuple;
717 fmt = PyString_FromString("[Errno %s] %s");
718 if (!fmt)
719 return NULL;
721 tuple = PyTuple_New(2);
722 if (!tuple) {
723 Py_DECREF(fmt);
724 return NULL;
727 if (self->myerrno) {
728 Py_INCREF(self->myerrno);
729 PyTuple_SET_ITEM(tuple, 0, self->myerrno);
731 else {
732 Py_INCREF(Py_None);
733 PyTuple_SET_ITEM(tuple, 0, Py_None);
735 if (self->strerror) {
736 Py_INCREF(self->strerror);
737 PyTuple_SET_ITEM(tuple, 1, self->strerror);
739 else {
740 Py_INCREF(Py_None);
741 PyTuple_SET_ITEM(tuple, 1, Py_None);
744 rtnval = PyString_Format(fmt, tuple);
746 Py_DECREF(fmt);
747 Py_DECREF(tuple);
749 else
750 rtnval = BaseException_str((PyBaseExceptionObject *)self);
752 return rtnval;
755 static PyMemberDef EnvironmentError_members[] = {
756 {"errno", T_OBJECT, offsetof(PyEnvironmentErrorObject, myerrno), 0,
757 PyDoc_STR("exception errno")},
758 {"strerror", T_OBJECT, offsetof(PyEnvironmentErrorObject, strerror), 0,
759 PyDoc_STR("exception strerror")},
760 {"filename", T_OBJECT, offsetof(PyEnvironmentErrorObject, filename), 0,
761 PyDoc_STR("exception filename")},
762 {NULL} /* Sentinel */
766 static PyObject *
767 EnvironmentError_reduce(PyEnvironmentErrorObject *self)
769 PyObject *args = self->args;
770 PyObject *res = NULL, *tmp;
772 /* self->args is only the first two real arguments if there was a
773 * file name given to EnvironmentError. */
774 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
775 args = PyTuple_New(3);
776 if (!args) return NULL;
778 tmp = PyTuple_GET_ITEM(self->args, 0);
779 Py_INCREF(tmp);
780 PyTuple_SET_ITEM(args, 0, tmp);
782 tmp = PyTuple_GET_ITEM(self->args, 1);
783 Py_INCREF(tmp);
784 PyTuple_SET_ITEM(args, 1, tmp);
786 Py_INCREF(self->filename);
787 PyTuple_SET_ITEM(args, 2, self->filename);
788 } else
789 Py_INCREF(args);
791 if (self->dict)
792 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
793 else
794 res = PyTuple_Pack(2, Py_TYPE(self), args);
795 Py_DECREF(args);
796 return res;
800 static PyMethodDef EnvironmentError_methods[] = {
801 {"__reduce__", (PyCFunction)EnvironmentError_reduce, METH_NOARGS},
802 {NULL}
805 ComplexExtendsException(PyExc_StandardError, EnvironmentError,
806 EnvironmentError, EnvironmentError_dealloc,
807 EnvironmentError_methods, EnvironmentError_members,
808 EnvironmentError_str,
809 "Base class for I/O related errors.");
813 * IOError extends EnvironmentError
815 MiddlingExtendsException(PyExc_EnvironmentError, IOError,
816 EnvironmentError, "I/O operation failed.");
820 * OSError extends EnvironmentError
822 MiddlingExtendsException(PyExc_EnvironmentError, OSError,
823 EnvironmentError, "OS system call failed.");
827 * WindowsError extends OSError
829 #ifdef MS_WINDOWS
830 #include "errmap.h"
832 static int
833 WindowsError_clear(PyWindowsErrorObject *self)
835 Py_CLEAR(self->myerrno);
836 Py_CLEAR(self->strerror);
837 Py_CLEAR(self->filename);
838 Py_CLEAR(self->winerror);
839 return BaseException_clear((PyBaseExceptionObject *)self);
842 static void
843 WindowsError_dealloc(PyWindowsErrorObject *self)
845 _PyObject_GC_UNTRACK(self);
846 WindowsError_clear(self);
847 Py_TYPE(self)->tp_free((PyObject *)self);
850 static int
851 WindowsError_traverse(PyWindowsErrorObject *self, visitproc visit, void *arg)
853 Py_VISIT(self->myerrno);
854 Py_VISIT(self->strerror);
855 Py_VISIT(self->filename);
856 Py_VISIT(self->winerror);
857 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
860 static int
861 WindowsError_init(PyWindowsErrorObject *self, PyObject *args, PyObject *kwds)
863 PyObject *o_errcode = NULL;
864 long errcode;
865 long posix_errno;
867 if (EnvironmentError_init((PyEnvironmentErrorObject *)self, args, kwds)
868 == -1)
869 return -1;
871 if (self->myerrno == NULL)
872 return 0;
874 /* Set errno to the POSIX errno, and winerror to the Win32
875 error code. */
876 errcode = PyInt_AsLong(self->myerrno);
877 if (errcode == -1 && PyErr_Occurred())
878 return -1;
879 posix_errno = winerror_to_errno(errcode);
881 Py_CLEAR(self->winerror);
882 self->winerror = self->myerrno;
884 o_errcode = PyInt_FromLong(posix_errno);
885 if (!o_errcode)
886 return -1;
888 self->myerrno = o_errcode;
890 return 0;
894 static PyObject *
895 WindowsError_str(PyWindowsErrorObject *self)
897 PyObject *rtnval = NULL;
899 if (self->filename) {
900 PyObject *fmt;
901 PyObject *repr;
902 PyObject *tuple;
904 fmt = PyString_FromString("[Error %s] %s: %s");
905 if (!fmt)
906 return NULL;
908 repr = PyObject_Repr(self->filename);
909 if (!repr) {
910 Py_DECREF(fmt);
911 return NULL;
913 tuple = PyTuple_New(3);
914 if (!tuple) {
915 Py_DECREF(repr);
916 Py_DECREF(fmt);
917 return NULL;
920 if (self->winerror) {
921 Py_INCREF(self->winerror);
922 PyTuple_SET_ITEM(tuple, 0, self->winerror);
924 else {
925 Py_INCREF(Py_None);
926 PyTuple_SET_ITEM(tuple, 0, Py_None);
928 if (self->strerror) {
929 Py_INCREF(self->strerror);
930 PyTuple_SET_ITEM(tuple, 1, self->strerror);
932 else {
933 Py_INCREF(Py_None);
934 PyTuple_SET_ITEM(tuple, 1, Py_None);
937 PyTuple_SET_ITEM(tuple, 2, repr);
939 rtnval = PyString_Format(fmt, tuple);
941 Py_DECREF(fmt);
942 Py_DECREF(tuple);
944 else if (self->winerror && self->strerror) {
945 PyObject *fmt;
946 PyObject *tuple;
948 fmt = PyString_FromString("[Error %s] %s");
949 if (!fmt)
950 return NULL;
952 tuple = PyTuple_New(2);
953 if (!tuple) {
954 Py_DECREF(fmt);
955 return NULL;
958 if (self->winerror) {
959 Py_INCREF(self->winerror);
960 PyTuple_SET_ITEM(tuple, 0, self->winerror);
962 else {
963 Py_INCREF(Py_None);
964 PyTuple_SET_ITEM(tuple, 0, Py_None);
966 if (self->strerror) {
967 Py_INCREF(self->strerror);
968 PyTuple_SET_ITEM(tuple, 1, self->strerror);
970 else {
971 Py_INCREF(Py_None);
972 PyTuple_SET_ITEM(tuple, 1, Py_None);
975 rtnval = PyString_Format(fmt, tuple);
977 Py_DECREF(fmt);
978 Py_DECREF(tuple);
980 else
981 rtnval = EnvironmentError_str((PyEnvironmentErrorObject *)self);
983 return rtnval;
986 static PyMemberDef WindowsError_members[] = {
987 {"errno", T_OBJECT, offsetof(PyWindowsErrorObject, myerrno), 0,
988 PyDoc_STR("POSIX exception code")},
989 {"strerror", T_OBJECT, offsetof(PyWindowsErrorObject, strerror), 0,
990 PyDoc_STR("exception strerror")},
991 {"filename", T_OBJECT, offsetof(PyWindowsErrorObject, filename), 0,
992 PyDoc_STR("exception filename")},
993 {"winerror", T_OBJECT, offsetof(PyWindowsErrorObject, winerror), 0,
994 PyDoc_STR("Win32 exception code")},
995 {NULL} /* Sentinel */
998 ComplexExtendsException(PyExc_OSError, WindowsError, WindowsError,
999 WindowsError_dealloc, 0, WindowsError_members,
1000 WindowsError_str, "MS-Windows OS system call failed.");
1002 #endif /* MS_WINDOWS */
1006 * VMSError extends OSError (I think)
1008 #ifdef __VMS
1009 MiddlingExtendsException(PyExc_OSError, VMSError, EnvironmentError,
1010 "OpenVMS OS system call failed.");
1011 #endif
1015 * EOFError extends StandardError
1017 SimpleExtendsException(PyExc_StandardError, EOFError,
1018 "Read beyond end of file.");
1022 * RuntimeError extends StandardError
1024 SimpleExtendsException(PyExc_StandardError, RuntimeError,
1025 "Unspecified run-time error.");
1029 * NotImplementedError extends RuntimeError
1031 SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1032 "Method or function hasn't been implemented yet.");
1035 * NameError extends StandardError
1037 SimpleExtendsException(PyExc_StandardError, NameError,
1038 "Name not found globally.");
1041 * UnboundLocalError extends NameError
1043 SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1044 "Local name referenced but not bound to a value.");
1047 * AttributeError extends StandardError
1049 SimpleExtendsException(PyExc_StandardError, AttributeError,
1050 "Attribute not found.");
1054 * SyntaxError extends StandardError
1057 static int
1058 SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1060 PyObject *info = NULL;
1061 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1063 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1064 return -1;
1066 if (lenargs >= 1) {
1067 Py_CLEAR(self->msg);
1068 self->msg = PyTuple_GET_ITEM(args, 0);
1069 Py_INCREF(self->msg);
1071 if (lenargs == 2) {
1072 info = PyTuple_GET_ITEM(args, 1);
1073 info = PySequence_Tuple(info);
1074 if (!info) return -1;
1076 if (PyTuple_GET_SIZE(info) != 4) {
1077 /* not a very good error message, but it's what Python 2.4 gives */
1078 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1079 Py_DECREF(info);
1080 return -1;
1083 Py_CLEAR(self->filename);
1084 self->filename = PyTuple_GET_ITEM(info, 0);
1085 Py_INCREF(self->filename);
1087 Py_CLEAR(self->lineno);
1088 self->lineno = PyTuple_GET_ITEM(info, 1);
1089 Py_INCREF(self->lineno);
1091 Py_CLEAR(self->offset);
1092 self->offset = PyTuple_GET_ITEM(info, 2);
1093 Py_INCREF(self->offset);
1095 Py_CLEAR(self->text);
1096 self->text = PyTuple_GET_ITEM(info, 3);
1097 Py_INCREF(self->text);
1099 Py_DECREF(info);
1101 return 0;
1104 static int
1105 SyntaxError_clear(PySyntaxErrorObject *self)
1107 Py_CLEAR(self->msg);
1108 Py_CLEAR(self->filename);
1109 Py_CLEAR(self->lineno);
1110 Py_CLEAR(self->offset);
1111 Py_CLEAR(self->text);
1112 Py_CLEAR(self->print_file_and_line);
1113 return BaseException_clear((PyBaseExceptionObject *)self);
1116 static void
1117 SyntaxError_dealloc(PySyntaxErrorObject *self)
1119 _PyObject_GC_UNTRACK(self);
1120 SyntaxError_clear(self);
1121 Py_TYPE(self)->tp_free((PyObject *)self);
1124 static int
1125 SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1127 Py_VISIT(self->msg);
1128 Py_VISIT(self->filename);
1129 Py_VISIT(self->lineno);
1130 Py_VISIT(self->offset);
1131 Py_VISIT(self->text);
1132 Py_VISIT(self->print_file_and_line);
1133 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1136 /* This is called "my_basename" instead of just "basename" to avoid name
1137 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1138 defined, and Python does define that. */
1139 static char *
1140 my_basename(char *name)
1142 char *cp = name;
1143 char *result = name;
1145 if (name == NULL)
1146 return "???";
1147 while (*cp != '\0') {
1148 if (*cp == SEP)
1149 result = cp + 1;
1150 ++cp;
1152 return result;
1156 static PyObject *
1157 SyntaxError_str(PySyntaxErrorObject *self)
1159 PyObject *str;
1160 PyObject *result;
1161 int have_filename = 0;
1162 int have_lineno = 0;
1163 char *buffer = NULL;
1164 Py_ssize_t bufsize;
1166 if (self->msg)
1167 str = PyObject_Str(self->msg);
1168 else
1169 str = PyObject_Str(Py_None);
1170 if (!str) return NULL;
1171 /* Don't fiddle with non-string return (shouldn't happen anyway) */
1172 if (!PyString_Check(str)) return str;
1174 /* XXX -- do all the additional formatting with filename and
1175 lineno here */
1177 have_filename = (self->filename != NULL) &&
1178 PyString_Check(self->filename);
1179 have_lineno = (self->lineno != NULL) && PyInt_Check(self->lineno);
1181 if (!have_filename && !have_lineno)
1182 return str;
1184 bufsize = PyString_GET_SIZE(str) + 64;
1185 if (have_filename)
1186 bufsize += PyString_GET_SIZE(self->filename);
1188 buffer = PyMem_MALLOC(bufsize);
1189 if (buffer == NULL)
1190 return str;
1192 if (have_filename && have_lineno)
1193 PyOS_snprintf(buffer, bufsize, "%s (%s, line %ld)",
1194 PyString_AS_STRING(str),
1195 my_basename(PyString_AS_STRING(self->filename)),
1196 PyInt_AsLong(self->lineno));
1197 else if (have_filename)
1198 PyOS_snprintf(buffer, bufsize, "%s (%s)",
1199 PyString_AS_STRING(str),
1200 my_basename(PyString_AS_STRING(self->filename)));
1201 else /* only have_lineno */
1202 PyOS_snprintf(buffer, bufsize, "%s (line %ld)",
1203 PyString_AS_STRING(str),
1204 PyInt_AsLong(self->lineno));
1206 result = PyString_FromString(buffer);
1207 PyMem_FREE(buffer);
1209 if (result == NULL)
1210 result = str;
1211 else
1212 Py_DECREF(str);
1213 return result;
1216 static PyMemberDef SyntaxError_members[] = {
1217 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1218 PyDoc_STR("exception msg")},
1219 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1220 PyDoc_STR("exception filename")},
1221 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1222 PyDoc_STR("exception lineno")},
1223 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1224 PyDoc_STR("exception offset")},
1225 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1226 PyDoc_STR("exception text")},
1227 {"print_file_and_line", T_OBJECT,
1228 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1229 PyDoc_STR("exception print_file_and_line")},
1230 {NULL} /* Sentinel */
1233 ComplexExtendsException(PyExc_StandardError, SyntaxError, SyntaxError,
1234 SyntaxError_dealloc, 0, SyntaxError_members,
1235 SyntaxError_str, "Invalid syntax.");
1239 * IndentationError extends SyntaxError
1241 MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1242 "Improper indentation.");
1246 * TabError extends IndentationError
1248 MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1249 "Improper mixture of spaces and tabs.");
1253 * LookupError extends StandardError
1255 SimpleExtendsException(PyExc_StandardError, LookupError,
1256 "Base class for lookup errors.");
1260 * IndexError extends LookupError
1262 SimpleExtendsException(PyExc_LookupError, IndexError,
1263 "Sequence index out of range.");
1267 * KeyError extends LookupError
1269 static PyObject *
1270 KeyError_str(PyBaseExceptionObject *self)
1272 /* If args is a tuple of exactly one item, apply repr to args[0].
1273 This is done so that e.g. the exception raised by {}[''] prints
1274 KeyError: ''
1275 rather than the confusing
1276 KeyError
1277 alone. The downside is that if KeyError is raised with an explanatory
1278 string, that string will be displayed in quotes. Too bad.
1279 If args is anything else, use the default BaseException__str__().
1281 if (PyTuple_GET_SIZE(self->args) == 1) {
1282 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
1284 return BaseException_str(self);
1287 ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
1288 0, 0, 0, KeyError_str, "Mapping key not found.");
1292 * ValueError extends StandardError
1294 SimpleExtendsException(PyExc_StandardError, ValueError,
1295 "Inappropriate argument value (of correct type).");
1298 * UnicodeError extends ValueError
1301 SimpleExtendsException(PyExc_ValueError, UnicodeError,
1302 "Unicode related error.");
1304 #ifdef Py_USING_UNICODE
1305 static PyObject *
1306 get_string(PyObject *attr, const char *name)
1308 if (!attr) {
1309 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1310 return NULL;
1313 if (!PyString_Check(attr)) {
1314 PyErr_Format(PyExc_TypeError, "%.200s attribute must be str", name);
1315 return NULL;
1317 Py_INCREF(attr);
1318 return attr;
1322 static int
1323 set_string(PyObject **attr, const char *value)
1325 PyObject *obj = PyString_FromString(value);
1326 if (!obj)
1327 return -1;
1328 Py_CLEAR(*attr);
1329 *attr = obj;
1330 return 0;
1334 static PyObject *
1335 get_unicode(PyObject *attr, const char *name)
1337 if (!attr) {
1338 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1339 return NULL;
1342 if (!PyUnicode_Check(attr)) {
1343 PyErr_Format(PyExc_TypeError,
1344 "%.200s attribute must be unicode", name);
1345 return NULL;
1347 Py_INCREF(attr);
1348 return attr;
1351 PyObject *
1352 PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1354 return get_string(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
1357 PyObject *
1358 PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1360 return get_string(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
1363 PyObject *
1364 PyUnicodeEncodeError_GetObject(PyObject *exc)
1366 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1369 PyObject *
1370 PyUnicodeDecodeError_GetObject(PyObject *exc)
1372 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
1375 PyObject *
1376 PyUnicodeTranslateError_GetObject(PyObject *exc)
1378 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1382 PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1384 Py_ssize_t size;
1385 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1386 "object");
1387 if (!obj)
1388 return -1;
1389 *start = ((PyUnicodeErrorObject *)exc)->start;
1390 size = PyUnicode_GET_SIZE(obj);
1391 if (*start<0)
1392 *start = 0; /*XXX check for values <0*/
1393 if (*start>=size)
1394 *start = size-1;
1395 Py_DECREF(obj);
1396 return 0;
1401 PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1403 Py_ssize_t size;
1404 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object,
1405 "object");
1406 if (!obj)
1407 return -1;
1408 size = PyString_GET_SIZE(obj);
1409 *start = ((PyUnicodeErrorObject *)exc)->start;
1410 if (*start<0)
1411 *start = 0;
1412 if (*start>=size)
1413 *start = size-1;
1414 Py_DECREF(obj);
1415 return 0;
1420 PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1422 return PyUnicodeEncodeError_GetStart(exc, start);
1427 PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1429 ((PyUnicodeErrorObject *)exc)->start = start;
1430 return 0;
1435 PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1437 ((PyUnicodeErrorObject *)exc)->start = start;
1438 return 0;
1443 PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1445 ((PyUnicodeErrorObject *)exc)->start = start;
1446 return 0;
1451 PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1453 Py_ssize_t size;
1454 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1455 "object");
1456 if (!obj)
1457 return -1;
1458 *end = ((PyUnicodeErrorObject *)exc)->end;
1459 size = PyUnicode_GET_SIZE(obj);
1460 if (*end<1)
1461 *end = 1;
1462 if (*end>size)
1463 *end = size;
1464 Py_DECREF(obj);
1465 return 0;
1470 PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1472 Py_ssize_t size;
1473 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object,
1474 "object");
1475 if (!obj)
1476 return -1;
1477 *end = ((PyUnicodeErrorObject *)exc)->end;
1478 size = PyString_GET_SIZE(obj);
1479 if (*end<1)
1480 *end = 1;
1481 if (*end>size)
1482 *end = size;
1483 Py_DECREF(obj);
1484 return 0;
1489 PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1491 return PyUnicodeEncodeError_GetEnd(exc, start);
1496 PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1498 ((PyUnicodeErrorObject *)exc)->end = end;
1499 return 0;
1504 PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1506 ((PyUnicodeErrorObject *)exc)->end = end;
1507 return 0;
1512 PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1514 ((PyUnicodeErrorObject *)exc)->end = end;
1515 return 0;
1518 PyObject *
1519 PyUnicodeEncodeError_GetReason(PyObject *exc)
1521 return get_string(((PyUnicodeErrorObject *)exc)->reason, "reason");
1525 PyObject *
1526 PyUnicodeDecodeError_GetReason(PyObject *exc)
1528 return get_string(((PyUnicodeErrorObject *)exc)->reason, "reason");
1532 PyObject *
1533 PyUnicodeTranslateError_GetReason(PyObject *exc)
1535 return get_string(((PyUnicodeErrorObject *)exc)->reason, "reason");
1540 PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1542 return set_string(&((PyUnicodeErrorObject *)exc)->reason, reason);
1547 PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1549 return set_string(&((PyUnicodeErrorObject *)exc)->reason, reason);
1554 PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1556 return set_string(&((PyUnicodeErrorObject *)exc)->reason, reason);
1560 static int
1561 UnicodeError_init(PyUnicodeErrorObject *self, PyObject *args, PyObject *kwds,
1562 PyTypeObject *objecttype)
1564 Py_CLEAR(self->encoding);
1565 Py_CLEAR(self->object);
1566 Py_CLEAR(self->reason);
1568 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1569 &PyString_Type, &self->encoding,
1570 objecttype, &self->object,
1571 &self->start,
1572 &self->end,
1573 &PyString_Type, &self->reason)) {
1574 self->encoding = self->object = self->reason = NULL;
1575 return -1;
1578 Py_INCREF(self->encoding);
1579 Py_INCREF(self->object);
1580 Py_INCREF(self->reason);
1582 return 0;
1585 static int
1586 UnicodeError_clear(PyUnicodeErrorObject *self)
1588 Py_CLEAR(self->encoding);
1589 Py_CLEAR(self->object);
1590 Py_CLEAR(self->reason);
1591 return BaseException_clear((PyBaseExceptionObject *)self);
1594 static void
1595 UnicodeError_dealloc(PyUnicodeErrorObject *self)
1597 _PyObject_GC_UNTRACK(self);
1598 UnicodeError_clear(self);
1599 Py_TYPE(self)->tp_free((PyObject *)self);
1602 static int
1603 UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1605 Py_VISIT(self->encoding);
1606 Py_VISIT(self->object);
1607 Py_VISIT(self->reason);
1608 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1611 static PyMemberDef UnicodeError_members[] = {
1612 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1613 PyDoc_STR("exception encoding")},
1614 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1615 PyDoc_STR("exception object")},
1616 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
1617 PyDoc_STR("exception start")},
1618 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
1619 PyDoc_STR("exception end")},
1620 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1621 PyDoc_STR("exception reason")},
1622 {NULL} /* Sentinel */
1627 * UnicodeEncodeError extends UnicodeError
1630 static int
1631 UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1633 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1634 return -1;
1635 return UnicodeError_init((PyUnicodeErrorObject *)self, args,
1636 kwds, &PyUnicode_Type);
1639 static PyObject *
1640 UnicodeEncodeError_str(PyObject *self)
1642 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
1644 if (uself->end==uself->start+1) {
1645 int badchar = (int)PyUnicode_AS_UNICODE(uself->object)[uself->start];
1646 char badchar_str[20];
1647 if (badchar <= 0xff)
1648 PyOS_snprintf(badchar_str, sizeof(badchar_str), "x%02x", badchar);
1649 else if (badchar <= 0xffff)
1650 PyOS_snprintf(badchar_str, sizeof(badchar_str), "u%04x", badchar);
1651 else
1652 PyOS_snprintf(badchar_str, sizeof(badchar_str), "U%08x", badchar);
1653 return PyString_FromFormat(
1654 "'%.400s' codec can't encode character u'\\%s' in position %zd: %.400s",
1655 PyString_AS_STRING(uself->encoding),
1656 badchar_str,
1657 uself->start,
1658 PyString_AS_STRING(uself->reason)
1661 return PyString_FromFormat(
1662 "'%.400s' codec can't encode characters in position %zd-%zd: %.400s",
1663 PyString_AS_STRING(uself->encoding),
1664 uself->start,
1665 uself->end-1,
1666 PyString_AS_STRING(uself->reason)
1670 static PyTypeObject _PyExc_UnicodeEncodeError = {
1671 PyObject_HEAD_INIT(NULL)
1673 EXC_MODULE_NAME "UnicodeEncodeError",
1674 sizeof(PyUnicodeErrorObject), 0,
1675 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1676 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1677 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1678 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1679 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
1680 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
1681 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
1683 PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1685 PyObject *
1686 PyUnicodeEncodeError_Create(
1687 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1688 Py_ssize_t start, Py_ssize_t end, const char *reason)
1690 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
1691 encoding, object, length, start, end, reason);
1696 * UnicodeDecodeError extends UnicodeError
1699 static int
1700 UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1702 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1703 return -1;
1704 return UnicodeError_init((PyUnicodeErrorObject *)self, args,
1705 kwds, &PyString_Type);
1708 static PyObject *
1709 UnicodeDecodeError_str(PyObject *self)
1711 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
1713 if (uself->end==uself->start+1) {
1714 /* FromFormat does not support %02x, so format that separately */
1715 char byte[4];
1716 PyOS_snprintf(byte, sizeof(byte), "%02x",
1717 ((int)PyString_AS_STRING(uself->object)[uself->start])&0xff);
1718 return PyString_FromFormat(
1719 "'%.400s' codec can't decode byte 0x%s in position %zd: %.400s",
1720 PyString_AS_STRING(uself->encoding),
1721 byte,
1722 uself->start,
1723 PyString_AS_STRING(uself->reason)
1726 return PyString_FromFormat(
1727 "'%.400s' codec can't decode bytes in position %zd-%zd: %.400s",
1728 PyString_AS_STRING(uself->encoding),
1729 uself->start,
1730 uself->end-1,
1731 PyString_AS_STRING(uself->reason)
1735 static PyTypeObject _PyExc_UnicodeDecodeError = {
1736 PyObject_HEAD_INIT(NULL)
1738 EXC_MODULE_NAME "UnicodeDecodeError",
1739 sizeof(PyUnicodeErrorObject), 0,
1740 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1741 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
1742 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1743 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
1744 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
1745 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
1746 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
1748 PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
1750 PyObject *
1751 PyUnicodeDecodeError_Create(
1752 const char *encoding, const char *object, Py_ssize_t length,
1753 Py_ssize_t start, Py_ssize_t end, const char *reason)
1755 assert(length < INT_MAX);
1756 assert(start < INT_MAX);
1757 assert(end < INT_MAX);
1758 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "ss#nns",
1759 encoding, object, length, start, end, reason);
1764 * UnicodeTranslateError extends UnicodeError
1767 static int
1768 UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
1769 PyObject *kwds)
1771 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1772 return -1;
1774 Py_CLEAR(self->object);
1775 Py_CLEAR(self->reason);
1777 if (!PyArg_ParseTuple(args, "O!nnO!",
1778 &PyUnicode_Type, &self->object,
1779 &self->start,
1780 &self->end,
1781 &PyString_Type, &self->reason)) {
1782 self->object = self->reason = NULL;
1783 return -1;
1786 Py_INCREF(self->object);
1787 Py_INCREF(self->reason);
1789 return 0;
1793 static PyObject *
1794 UnicodeTranslateError_str(PyObject *self)
1796 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
1798 if (uself->end==uself->start+1) {
1799 int badchar = (int)PyUnicode_AS_UNICODE(uself->object)[uself->start];
1800 char badchar_str[20];
1801 if (badchar <= 0xff)
1802 PyOS_snprintf(badchar_str, sizeof(badchar_str), "x%02x", badchar);
1803 else if (badchar <= 0xffff)
1804 PyOS_snprintf(badchar_str, sizeof(badchar_str), "u%04x", badchar);
1805 else
1806 PyOS_snprintf(badchar_str, sizeof(badchar_str), "U%08x", badchar);
1807 return PyString_FromFormat(
1808 "can't translate character u'\\%s' in position %zd: %.400s",
1809 badchar_str,
1810 uself->start,
1811 PyString_AS_STRING(uself->reason)
1814 return PyString_FromFormat(
1815 "can't translate characters in position %zd-%zd: %.400s",
1816 uself->start,
1817 uself->end-1,
1818 PyString_AS_STRING(uself->reason)
1822 static PyTypeObject _PyExc_UnicodeTranslateError = {
1823 PyObject_HEAD_INIT(NULL)
1825 EXC_MODULE_NAME "UnicodeTranslateError",
1826 sizeof(PyUnicodeErrorObject), 0,
1827 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1828 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
1829 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1830 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
1831 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
1832 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
1833 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
1835 PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
1837 PyObject *
1838 PyUnicodeTranslateError_Create(
1839 const Py_UNICODE *object, Py_ssize_t length,
1840 Py_ssize_t start, Py_ssize_t end, const char *reason)
1842 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
1843 object, length, start, end, reason);
1845 #endif
1849 * AssertionError extends StandardError
1851 SimpleExtendsException(PyExc_StandardError, AssertionError,
1852 "Assertion failed.");
1856 * ArithmeticError extends StandardError
1858 SimpleExtendsException(PyExc_StandardError, ArithmeticError,
1859 "Base class for arithmetic errors.");
1863 * FloatingPointError extends ArithmeticError
1865 SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
1866 "Floating point operation failed.");
1870 * OverflowError extends ArithmeticError
1872 SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
1873 "Result too large to be represented.");
1877 * ZeroDivisionError extends ArithmeticError
1879 SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
1880 "Second argument to a division or modulo operation was zero.");
1884 * SystemError extends StandardError
1886 SimpleExtendsException(PyExc_StandardError, SystemError,
1887 "Internal error in the Python interpreter.\n"
1888 "\n"
1889 "Please report this to the Python maintainer, along with the traceback,\n"
1890 "the Python version, and the hardware/OS platform and version.");
1894 * ReferenceError extends StandardError
1896 SimpleExtendsException(PyExc_StandardError, ReferenceError,
1897 "Weak ref proxy used after referent went away.");
1901 * MemoryError extends StandardError
1903 SimpleExtendsException(PyExc_StandardError, MemoryError, "Out of memory.");
1906 * BufferError extends StandardError
1908 SimpleExtendsException(PyExc_StandardError, BufferError, "Buffer error.");
1911 /* Warning category docstrings */
1914 * Warning extends Exception
1916 SimpleExtendsException(PyExc_Exception, Warning,
1917 "Base class for warning categories.");
1921 * UserWarning extends Warning
1923 SimpleExtendsException(PyExc_Warning, UserWarning,
1924 "Base class for warnings generated by user code.");
1928 * DeprecationWarning extends Warning
1930 SimpleExtendsException(PyExc_Warning, DeprecationWarning,
1931 "Base class for warnings about deprecated features.");
1935 * PendingDeprecationWarning extends Warning
1937 SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
1938 "Base class for warnings about features which will be deprecated\n"
1939 "in the future.");
1943 * SyntaxWarning extends Warning
1945 SimpleExtendsException(PyExc_Warning, SyntaxWarning,
1946 "Base class for warnings about dubious syntax.");
1950 * RuntimeWarning extends Warning
1952 SimpleExtendsException(PyExc_Warning, RuntimeWarning,
1953 "Base class for warnings about dubious runtime behavior.");
1957 * FutureWarning extends Warning
1959 SimpleExtendsException(PyExc_Warning, FutureWarning,
1960 "Base class for warnings about constructs that will change semantically\n"
1961 "in the future.");
1965 * ImportWarning extends Warning
1967 SimpleExtendsException(PyExc_Warning, ImportWarning,
1968 "Base class for warnings about probable mistakes in module imports");
1972 * UnicodeWarning extends Warning
1974 SimpleExtendsException(PyExc_Warning, UnicodeWarning,
1975 "Base class for warnings about Unicode related problems, mostly\n"
1976 "related to conversion problems.");
1979 * BytesWarning extends Warning
1981 SimpleExtendsException(PyExc_Warning, BytesWarning,
1982 "Base class for warnings about bytes and buffer related problems, mostly\n"
1983 "related to conversion from str or comparing to str.");
1985 /* Pre-computed MemoryError instance. Best to create this as early as
1986 * possible and not wait until a MemoryError is actually raised!
1988 PyObject *PyExc_MemoryErrorInst=NULL;
1990 /* Pre-computed RuntimeError instance for when recursion depth is reached.
1991 Meant to be used when normalizing the exception for exceeding the recursion
1992 depth will cause its own infinite recursion.
1994 PyObject *PyExc_RecursionErrorInst = NULL;
1996 /* module global functions */
1997 static PyMethodDef functions[] = {
1998 /* Sentinel */
1999 {NULL, NULL}
2002 #define PRE_INIT(TYPE) if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2003 Py_FatalError("exceptions bootstrapping error.");
2005 #define POST_INIT(TYPE) Py_INCREF(PyExc_ ## TYPE); \
2006 PyModule_AddObject(m, # TYPE, PyExc_ ## TYPE); \
2007 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2008 Py_FatalError("Module dictionary insertion problem.");
2011 PyMODINIT_FUNC
2012 _PyExc_Init(void)
2014 PyObject *m, *bltinmod, *bdict;
2016 PRE_INIT(BaseException)
2017 PRE_INIT(Exception)
2018 PRE_INIT(StandardError)
2019 PRE_INIT(TypeError)
2020 PRE_INIT(StopIteration)
2021 PRE_INIT(GeneratorExit)
2022 PRE_INIT(SystemExit)
2023 PRE_INIT(KeyboardInterrupt)
2024 PRE_INIT(ImportError)
2025 PRE_INIT(EnvironmentError)
2026 PRE_INIT(IOError)
2027 PRE_INIT(OSError)
2028 #ifdef MS_WINDOWS
2029 PRE_INIT(WindowsError)
2030 #endif
2031 #ifdef __VMS
2032 PRE_INIT(VMSError)
2033 #endif
2034 PRE_INIT(EOFError)
2035 PRE_INIT(RuntimeError)
2036 PRE_INIT(NotImplementedError)
2037 PRE_INIT(NameError)
2038 PRE_INIT(UnboundLocalError)
2039 PRE_INIT(AttributeError)
2040 PRE_INIT(SyntaxError)
2041 PRE_INIT(IndentationError)
2042 PRE_INIT(TabError)
2043 PRE_INIT(LookupError)
2044 PRE_INIT(IndexError)
2045 PRE_INIT(KeyError)
2046 PRE_INIT(ValueError)
2047 PRE_INIT(UnicodeError)
2048 #ifdef Py_USING_UNICODE
2049 PRE_INIT(UnicodeEncodeError)
2050 PRE_INIT(UnicodeDecodeError)
2051 PRE_INIT(UnicodeTranslateError)
2052 #endif
2053 PRE_INIT(AssertionError)
2054 PRE_INIT(ArithmeticError)
2055 PRE_INIT(FloatingPointError)
2056 PRE_INIT(OverflowError)
2057 PRE_INIT(ZeroDivisionError)
2058 PRE_INIT(SystemError)
2059 PRE_INIT(ReferenceError)
2060 PRE_INIT(MemoryError)
2061 PRE_INIT(BufferError)
2062 PRE_INIT(Warning)
2063 PRE_INIT(UserWarning)
2064 PRE_INIT(DeprecationWarning)
2065 PRE_INIT(PendingDeprecationWarning)
2066 PRE_INIT(SyntaxWarning)
2067 PRE_INIT(RuntimeWarning)
2068 PRE_INIT(FutureWarning)
2069 PRE_INIT(ImportWarning)
2070 PRE_INIT(UnicodeWarning)
2071 PRE_INIT(BytesWarning)
2073 m = Py_InitModule4("exceptions", functions, exceptions_doc,
2074 (PyObject *)NULL, PYTHON_API_VERSION);
2075 if (m == NULL) return;
2077 bltinmod = PyImport_ImportModule("__builtin__");
2078 if (bltinmod == NULL)
2079 Py_FatalError("exceptions bootstrapping error.");
2080 bdict = PyModule_GetDict(bltinmod);
2081 if (bdict == NULL)
2082 Py_FatalError("exceptions bootstrapping error.");
2084 POST_INIT(BaseException)
2085 POST_INIT(Exception)
2086 POST_INIT(StandardError)
2087 POST_INIT(TypeError)
2088 POST_INIT(StopIteration)
2089 POST_INIT(GeneratorExit)
2090 POST_INIT(SystemExit)
2091 POST_INIT(KeyboardInterrupt)
2092 POST_INIT(ImportError)
2093 POST_INIT(EnvironmentError)
2094 POST_INIT(IOError)
2095 POST_INIT(OSError)
2096 #ifdef MS_WINDOWS
2097 POST_INIT(WindowsError)
2098 #endif
2099 #ifdef __VMS
2100 POST_INIT(VMSError)
2101 #endif
2102 POST_INIT(EOFError)
2103 POST_INIT(RuntimeError)
2104 POST_INIT(NotImplementedError)
2105 POST_INIT(NameError)
2106 POST_INIT(UnboundLocalError)
2107 POST_INIT(AttributeError)
2108 POST_INIT(SyntaxError)
2109 POST_INIT(IndentationError)
2110 POST_INIT(TabError)
2111 POST_INIT(LookupError)
2112 POST_INIT(IndexError)
2113 POST_INIT(KeyError)
2114 POST_INIT(ValueError)
2115 POST_INIT(UnicodeError)
2116 #ifdef Py_USING_UNICODE
2117 POST_INIT(UnicodeEncodeError)
2118 POST_INIT(UnicodeDecodeError)
2119 POST_INIT(UnicodeTranslateError)
2120 #endif
2121 POST_INIT(AssertionError)
2122 POST_INIT(ArithmeticError)
2123 POST_INIT(FloatingPointError)
2124 POST_INIT(OverflowError)
2125 POST_INIT(ZeroDivisionError)
2126 POST_INIT(SystemError)
2127 POST_INIT(ReferenceError)
2128 POST_INIT(MemoryError)
2129 POST_INIT(BufferError)
2130 POST_INIT(Warning)
2131 POST_INIT(UserWarning)
2132 POST_INIT(DeprecationWarning)
2133 POST_INIT(PendingDeprecationWarning)
2134 POST_INIT(SyntaxWarning)
2135 POST_INIT(RuntimeWarning)
2136 POST_INIT(FutureWarning)
2137 POST_INIT(ImportWarning)
2138 POST_INIT(UnicodeWarning)
2139 POST_INIT(BytesWarning)
2141 PyExc_MemoryErrorInst = BaseException_new(&_PyExc_MemoryError, NULL, NULL);
2142 if (!PyExc_MemoryErrorInst)
2143 Py_FatalError("Cannot pre-allocate MemoryError instance");
2145 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL);
2146 if (!PyExc_RecursionErrorInst)
2147 Py_FatalError("Cannot pre-allocate RuntimeError instance for "
2148 "recursion errors");
2149 else {
2150 PyBaseExceptionObject *err_inst =
2151 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2152 PyObject *args_tuple;
2153 PyObject *exc_message;
2154 exc_message = PyString_FromString("maximum recursion depth exceeded");
2155 if (!exc_message)
2156 Py_FatalError("cannot allocate argument for RuntimeError "
2157 "pre-allocation");
2158 args_tuple = PyTuple_Pack(1, exc_message);
2159 if (!args_tuple)
2160 Py_FatalError("cannot allocate tuple for RuntimeError "
2161 "pre-allocation");
2162 Py_DECREF(exc_message);
2163 if (BaseException_init(err_inst, args_tuple, NULL))
2164 Py_FatalError("init of pre-allocated RuntimeError failed");
2165 Py_DECREF(args_tuple);
2168 Py_DECREF(bltinmod);
2171 void
2172 _PyExc_Fini(void)
2174 Py_CLEAR(PyExc_MemoryErrorInst);
2175 Py_CLEAR(PyExc_RecursionErrorInst);