Merged revisions 78818 via svnmerge from
[python/dscho.git] / Objects / exceptions.c
blob57fe9d78c1e0878164bddd3a9b22a31ffa97ba84
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"
13 /* NOTE: If the exception class hierarchy changes, don't forget to update
14 * Lib/test/exception_hierarchy.txt
18 * BaseException
20 static PyObject *
21 BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
23 PyBaseExceptionObject *self;
25 self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
26 if (!self)
27 return NULL;
28 /* the dict is created on the fly in PyObject_GenericSetAttr */
29 self->dict = NULL;
30 self->traceback = self->cause = self->context = NULL;
32 self->args = PyTuple_New(0);
33 if (!self->args) {
34 Py_DECREF(self);
35 return NULL;
38 return (PyObject *)self;
41 static int
42 BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
44 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
45 return -1;
47 Py_DECREF(self->args);
48 self->args = args;
49 Py_INCREF(self->args);
51 return 0;
54 static int
55 BaseException_clear(PyBaseExceptionObject *self)
57 Py_CLEAR(self->dict);
58 Py_CLEAR(self->args);
59 Py_CLEAR(self->traceback);
60 Py_CLEAR(self->cause);
61 Py_CLEAR(self->context);
62 return 0;
65 static void
66 BaseException_dealloc(PyBaseExceptionObject *self)
68 _PyObject_GC_UNTRACK(self);
69 BaseException_clear(self);
70 Py_TYPE(self)->tp_free((PyObject *)self);
73 static int
74 BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
76 Py_VISIT(self->dict);
77 Py_VISIT(self->args);
78 Py_VISIT(self->traceback);
79 Py_VISIT(self->cause);
80 Py_VISIT(self->context);
81 return 0;
84 static PyObject *
85 BaseException_str(PyBaseExceptionObject *self)
87 switch (PyTuple_GET_SIZE(self->args)) {
88 case 0:
89 return PyUnicode_FromString("");
90 case 1:
91 return PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
92 default:
93 return PyObject_Str(self->args);
97 static PyObject *
98 BaseException_repr(PyBaseExceptionObject *self)
100 char *name;
101 char *dot;
103 name = (char *)Py_TYPE(self)->tp_name;
104 dot = strrchr(name, '.');
105 if (dot != NULL) name = dot+1;
107 return PyUnicode_FromFormat("%s%R", name, self->args);
110 /* Pickling support */
111 static PyObject *
112 BaseException_reduce(PyBaseExceptionObject *self)
114 if (self->args && self->dict)
115 return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
116 else
117 return PyTuple_Pack(2, Py_TYPE(self), self->args);
121 * Needed for backward compatibility, since exceptions used to store
122 * all their attributes in the __dict__. Code is taken from cPickle's
123 * load_build function.
125 static PyObject *
126 BaseException_setstate(PyObject *self, PyObject *state)
128 PyObject *d_key, *d_value;
129 Py_ssize_t i = 0;
131 if (state != Py_None) {
132 if (!PyDict_Check(state)) {
133 PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
134 return NULL;
136 while (PyDict_Next(state, &i, &d_key, &d_value)) {
137 if (PyObject_SetAttr(self, d_key, d_value) < 0)
138 return NULL;
141 Py_RETURN_NONE;
144 static PyObject *
145 BaseException_with_traceback(PyObject *self, PyObject *tb) {
146 if (PyException_SetTraceback(self, tb))
147 return NULL;
149 Py_INCREF(self);
150 return self;
153 PyDoc_STRVAR(with_traceback_doc,
154 "Exception.with_traceback(tb) --\n\
155 set self.__traceback__ to tb and return self.");
158 static PyMethodDef BaseException_methods[] = {
159 {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
160 {"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
161 {"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O,
162 with_traceback_doc},
163 {NULL, NULL, 0, NULL},
167 static PyObject *
168 BaseException_get_dict(PyBaseExceptionObject *self)
170 if (self->dict == NULL) {
171 self->dict = PyDict_New();
172 if (!self->dict)
173 return NULL;
175 Py_INCREF(self->dict);
176 return self->dict;
179 static int
180 BaseException_set_dict(PyBaseExceptionObject *self, PyObject *val)
182 if (val == NULL) {
183 PyErr_SetString(PyExc_TypeError, "__dict__ may not be deleted");
184 return -1;
186 if (!PyDict_Check(val)) {
187 PyErr_SetString(PyExc_TypeError, "__dict__ must be a dictionary");
188 return -1;
190 Py_CLEAR(self->dict);
191 Py_INCREF(val);
192 self->dict = val;
193 return 0;
196 static PyObject *
197 BaseException_get_args(PyBaseExceptionObject *self)
199 if (self->args == NULL) {
200 Py_INCREF(Py_None);
201 return Py_None;
203 Py_INCREF(self->args);
204 return self->args;
207 static int
208 BaseException_set_args(PyBaseExceptionObject *self, PyObject *val)
210 PyObject *seq;
211 if (val == NULL) {
212 PyErr_SetString(PyExc_TypeError, "args may not be deleted");
213 return -1;
215 seq = PySequence_Tuple(val);
216 if (!seq) return -1;
217 Py_CLEAR(self->args);
218 self->args = seq;
219 return 0;
222 static PyObject *
223 BaseException_get_tb(PyBaseExceptionObject *self)
225 if (self->traceback == NULL) {
226 Py_INCREF(Py_None);
227 return Py_None;
229 Py_INCREF(self->traceback);
230 return self->traceback;
233 static int
234 BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb)
236 if (tb == NULL) {
237 PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted");
238 return -1;
240 else if (!(tb == Py_None || PyTraceBack_Check(tb))) {
241 PyErr_SetString(PyExc_TypeError,
242 "__traceback__ must be a traceback or None");
243 return -1;
246 Py_XINCREF(tb);
247 Py_XDECREF(self->traceback);
248 self->traceback = tb;
249 return 0;
252 static PyObject *
253 BaseException_get_context(PyObject *self) {
254 PyObject *res = PyException_GetContext(self);
255 if (res) return res; /* new reference already returned above */
256 Py_RETURN_NONE;
259 static int
260 BaseException_set_context(PyObject *self, PyObject *arg) {
261 if (arg == NULL) {
262 PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
263 return -1;
264 } else if (arg == Py_None) {
265 arg = NULL;
266 } else if (!PyExceptionInstance_Check(arg)) {
267 PyErr_SetString(PyExc_TypeError, "exception context must be None "
268 "or derive from BaseException");
269 return -1;
270 } else {
271 /* PyException_SetContext steals this reference */
272 Py_INCREF(arg);
274 PyException_SetContext(self, arg);
275 return 0;
278 static PyObject *
279 BaseException_get_cause(PyObject *self) {
280 PyObject *res = PyException_GetCause(self);
281 if (res) return res; /* new reference already returned above */
282 Py_RETURN_NONE;
285 static int
286 BaseException_set_cause(PyObject *self, PyObject *arg) {
287 if (arg == NULL) {
288 PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
289 return -1;
290 } else if (arg == Py_None) {
291 arg = NULL;
292 } else if (!PyExceptionInstance_Check(arg)) {
293 PyErr_SetString(PyExc_TypeError, "exception cause must be None "
294 "or derive from BaseException");
295 return -1;
296 } else {
297 /* PyException_SetCause steals this reference */
298 Py_INCREF(arg);
300 PyException_SetCause(self, arg);
301 return 0;
305 static PyGetSetDef BaseException_getset[] = {
306 {"__dict__", (getter)BaseException_get_dict, (setter)BaseException_set_dict},
307 {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
308 {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
309 {"__context__", (getter)BaseException_get_context,
310 (setter)BaseException_set_context, PyDoc_STR("exception context")},
311 {"__cause__", (getter)BaseException_get_cause,
312 (setter)BaseException_set_cause, PyDoc_STR("exception cause")},
313 {NULL},
317 PyObject *
318 PyException_GetTraceback(PyObject *self) {
319 PyBaseExceptionObject *base_self = (PyBaseExceptionObject *)self;
320 Py_XINCREF(base_self->traceback);
321 return base_self->traceback;
326 PyException_SetTraceback(PyObject *self, PyObject *tb) {
327 return BaseException_set_tb((PyBaseExceptionObject *)self, tb);
330 PyObject *
331 PyException_GetCause(PyObject *self) {
332 PyObject *cause = ((PyBaseExceptionObject *)self)->cause;
333 Py_XINCREF(cause);
334 return cause;
337 /* Steals a reference to cause */
338 void
339 PyException_SetCause(PyObject *self, PyObject *cause) {
340 PyObject *old_cause = ((PyBaseExceptionObject *)self)->cause;
341 ((PyBaseExceptionObject *)self)->cause = cause;
342 Py_XDECREF(old_cause);
345 PyObject *
346 PyException_GetContext(PyObject *self) {
347 PyObject *context = ((PyBaseExceptionObject *)self)->context;
348 Py_XINCREF(context);
349 return context;
352 /* Steals a reference to context */
353 void
354 PyException_SetContext(PyObject *self, PyObject *context) {
355 PyObject *old_context = ((PyBaseExceptionObject *)self)->context;
356 ((PyBaseExceptionObject *)self)->context = context;
357 Py_XDECREF(old_context);
361 static PyTypeObject _PyExc_BaseException = {
362 PyVarObject_HEAD_INIT(NULL, 0)
363 "BaseException", /*tp_name*/
364 sizeof(PyBaseExceptionObject), /*tp_basicsize*/
365 0, /*tp_itemsize*/
366 (destructor)BaseException_dealloc, /*tp_dealloc*/
367 0, /*tp_print*/
368 0, /*tp_getattr*/
369 0, /*tp_setattr*/
370 0, /* tp_reserved; */
371 (reprfunc)BaseException_repr, /*tp_repr*/
372 0, /*tp_as_number*/
373 0, /*tp_as_sequence*/
374 0, /*tp_as_mapping*/
375 0, /*tp_hash */
376 0, /*tp_call*/
377 (reprfunc)BaseException_str, /*tp_str*/
378 PyObject_GenericGetAttr, /*tp_getattro*/
379 PyObject_GenericSetAttr, /*tp_setattro*/
380 0, /*tp_as_buffer*/
381 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
382 Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
383 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
384 (traverseproc)BaseException_traverse, /* tp_traverse */
385 (inquiry)BaseException_clear, /* tp_clear */
386 0, /* tp_richcompare */
387 0, /* tp_weaklistoffset */
388 0, /* tp_iter */
389 0, /* tp_iternext */
390 BaseException_methods, /* tp_methods */
391 0, /* tp_members */
392 BaseException_getset, /* tp_getset */
393 0, /* tp_base */
394 0, /* tp_dict */
395 0, /* tp_descr_get */
396 0, /* tp_descr_set */
397 offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
398 (initproc)BaseException_init, /* tp_init */
399 0, /* tp_alloc */
400 BaseException_new, /* tp_new */
402 /* the CPython API expects exceptions to be (PyObject *) - both a hold-over
403 from the previous implmentation and also allowing Python objects to be used
404 in the API */
405 PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
407 /* note these macros omit the last semicolon so the macro invocation may
408 * include it and not look strange.
410 #define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
411 static PyTypeObject _PyExc_ ## EXCNAME = { \
412 PyVarObject_HEAD_INIT(NULL, 0) \
413 # EXCNAME, \
414 sizeof(PyBaseExceptionObject), \
415 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
416 0, 0, 0, 0, 0, 0, 0, \
417 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
418 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
419 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
420 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
421 (initproc)BaseException_init, 0, BaseException_new,\
422 }; \
423 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
425 #define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
426 static PyTypeObject _PyExc_ ## EXCNAME = { \
427 PyVarObject_HEAD_INIT(NULL, 0) \
428 # EXCNAME, \
429 sizeof(Py ## EXCSTORE ## Object), \
430 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
431 0, 0, 0, 0, 0, \
432 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
433 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
434 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
435 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
436 (initproc)EXCSTORE ## _init, 0, BaseException_new,\
437 }; \
438 PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
440 #define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDEALLOC, EXCMETHODS, EXCMEMBERS, EXCSTR, EXCDOC) \
441 static PyTypeObject _PyExc_ ## EXCNAME = { \
442 PyVarObject_HEAD_INIT(NULL, 0) \
443 # EXCNAME, \
444 sizeof(Py ## EXCSTORE ## Object), 0, \
445 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
446 (reprfunc)EXCSTR, 0, 0, 0, \
447 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
448 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
449 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
450 EXCMEMBERS, 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
458 * Exception extends BaseException
460 SimpleExtendsException(PyExc_BaseException, Exception,
461 "Common base class for all non-exit exceptions.");
465 * TypeError extends Exception
467 SimpleExtendsException(PyExc_Exception, TypeError,
468 "Inappropriate argument type.");
472 * StopIteration extends Exception
474 SimpleExtendsException(PyExc_Exception, StopIteration,
475 "Signal the end from iterator.__next__().");
479 * GeneratorExit extends BaseException
481 SimpleExtendsException(PyExc_BaseException, GeneratorExit,
482 "Request that a generator exit.");
486 * SystemExit extends BaseException
489 static int
490 SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
492 Py_ssize_t size = PyTuple_GET_SIZE(args);
494 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
495 return -1;
497 if (size == 0)
498 return 0;
499 Py_CLEAR(self->code);
500 if (size == 1)
501 self->code = PyTuple_GET_ITEM(args, 0);
502 else if (size > 1)
503 self->code = args;
504 Py_INCREF(self->code);
505 return 0;
508 static int
509 SystemExit_clear(PySystemExitObject *self)
511 Py_CLEAR(self->code);
512 return BaseException_clear((PyBaseExceptionObject *)self);
515 static void
516 SystemExit_dealloc(PySystemExitObject *self)
518 _PyObject_GC_UNTRACK(self);
519 SystemExit_clear(self);
520 Py_TYPE(self)->tp_free((PyObject *)self);
523 static int
524 SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
526 Py_VISIT(self->code);
527 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
530 static PyMemberDef SystemExit_members[] = {
531 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
532 PyDoc_STR("exception code")},
533 {NULL} /* Sentinel */
536 ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
537 SystemExit_dealloc, 0, SystemExit_members, 0,
538 "Request to exit from the interpreter.");
541 * KeyboardInterrupt extends BaseException
543 SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
544 "Program interrupted by user.");
548 * ImportError extends Exception
550 SimpleExtendsException(PyExc_Exception, ImportError,
551 "Import can't find module, or can't find name in module.");
555 * EnvironmentError extends Exception
558 /* Where a function has a single filename, such as open() or some
559 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
560 * called, giving a third argument which is the filename. But, so
561 * that old code using in-place unpacking doesn't break, e.g.:
563 * except IOError, (errno, strerror):
565 * we hack args so that it only contains two items. This also
566 * means we need our own __str__() which prints out the filename
567 * when it was supplied.
569 static int
570 EnvironmentError_init(PyEnvironmentErrorObject *self, PyObject *args,
571 PyObject *kwds)
573 PyObject *myerrno = NULL, *strerror = NULL, *filename = NULL;
574 PyObject *subslice = NULL;
576 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
577 return -1;
579 if (PyTuple_GET_SIZE(args) <= 1 || PyTuple_GET_SIZE(args) > 3) {
580 return 0;
583 if (!PyArg_UnpackTuple(args, "EnvironmentError", 2, 3,
584 &myerrno, &strerror, &filename)) {
585 return -1;
587 Py_CLEAR(self->myerrno); /* replacing */
588 self->myerrno = myerrno;
589 Py_INCREF(self->myerrno);
591 Py_CLEAR(self->strerror); /* replacing */
592 self->strerror = strerror;
593 Py_INCREF(self->strerror);
595 /* self->filename will remain Py_None otherwise */
596 if (filename != NULL) {
597 Py_CLEAR(self->filename); /* replacing */
598 self->filename = filename;
599 Py_INCREF(self->filename);
601 subslice = PyTuple_GetSlice(args, 0, 2);
602 if (!subslice)
603 return -1;
605 Py_DECREF(self->args); /* replacing args */
606 self->args = subslice;
608 return 0;
611 static int
612 EnvironmentError_clear(PyEnvironmentErrorObject *self)
614 Py_CLEAR(self->myerrno);
615 Py_CLEAR(self->strerror);
616 Py_CLEAR(self->filename);
617 return BaseException_clear((PyBaseExceptionObject *)self);
620 static void
621 EnvironmentError_dealloc(PyEnvironmentErrorObject *self)
623 _PyObject_GC_UNTRACK(self);
624 EnvironmentError_clear(self);
625 Py_TYPE(self)->tp_free((PyObject *)self);
628 static int
629 EnvironmentError_traverse(PyEnvironmentErrorObject *self, visitproc visit,
630 void *arg)
632 Py_VISIT(self->myerrno);
633 Py_VISIT(self->strerror);
634 Py_VISIT(self->filename);
635 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
638 static PyObject *
639 EnvironmentError_str(PyEnvironmentErrorObject *self)
641 if (self->filename)
642 return PyUnicode_FromFormat("[Errno %S] %S: %R",
643 self->myerrno ? self->myerrno: Py_None,
644 self->strerror ? self->strerror: Py_None,
645 self->filename);
646 else if (self->myerrno && self->strerror)
647 return PyUnicode_FromFormat("[Errno %S] %S",
648 self->myerrno ? self->myerrno: Py_None,
649 self->strerror ? self->strerror: Py_None);
650 else
651 return BaseException_str((PyBaseExceptionObject *)self);
654 static PyMemberDef EnvironmentError_members[] = {
655 {"errno", T_OBJECT, offsetof(PyEnvironmentErrorObject, myerrno), 0,
656 PyDoc_STR("exception errno")},
657 {"strerror", T_OBJECT, offsetof(PyEnvironmentErrorObject, strerror), 0,
658 PyDoc_STR("exception strerror")},
659 {"filename", T_OBJECT, offsetof(PyEnvironmentErrorObject, filename), 0,
660 PyDoc_STR("exception filename")},
661 {NULL} /* Sentinel */
665 static PyObject *
666 EnvironmentError_reduce(PyEnvironmentErrorObject *self)
668 PyObject *args = self->args;
669 PyObject *res = NULL, *tmp;
671 /* self->args is only the first two real arguments if there was a
672 * file name given to EnvironmentError. */
673 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
674 args = PyTuple_New(3);
675 if (!args) return NULL;
677 tmp = PyTuple_GET_ITEM(self->args, 0);
678 Py_INCREF(tmp);
679 PyTuple_SET_ITEM(args, 0, tmp);
681 tmp = PyTuple_GET_ITEM(self->args, 1);
682 Py_INCREF(tmp);
683 PyTuple_SET_ITEM(args, 1, tmp);
685 Py_INCREF(self->filename);
686 PyTuple_SET_ITEM(args, 2, self->filename);
687 } else
688 Py_INCREF(args);
690 if (self->dict)
691 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
692 else
693 res = PyTuple_Pack(2, Py_TYPE(self), args);
694 Py_DECREF(args);
695 return res;
699 static PyMethodDef EnvironmentError_methods[] = {
700 {"__reduce__", (PyCFunction)EnvironmentError_reduce, METH_NOARGS},
701 {NULL}
704 ComplexExtendsException(PyExc_Exception, EnvironmentError,
705 EnvironmentError, EnvironmentError_dealloc,
706 EnvironmentError_methods, EnvironmentError_members,
707 EnvironmentError_str,
708 "Base class for I/O related errors.");
712 * IOError extends EnvironmentError
714 MiddlingExtendsException(PyExc_EnvironmentError, IOError,
715 EnvironmentError, "I/O operation failed.");
719 * OSError extends EnvironmentError
721 MiddlingExtendsException(PyExc_EnvironmentError, OSError,
722 EnvironmentError, "OS system call failed.");
726 * WindowsError extends OSError
728 #ifdef MS_WINDOWS
729 #include "errmap.h"
731 static int
732 WindowsError_clear(PyWindowsErrorObject *self)
734 Py_CLEAR(self->myerrno);
735 Py_CLEAR(self->strerror);
736 Py_CLEAR(self->filename);
737 Py_CLEAR(self->winerror);
738 return BaseException_clear((PyBaseExceptionObject *)self);
741 static void
742 WindowsError_dealloc(PyWindowsErrorObject *self)
744 _PyObject_GC_UNTRACK(self);
745 WindowsError_clear(self);
746 Py_TYPE(self)->tp_free((PyObject *)self);
749 static int
750 WindowsError_traverse(PyWindowsErrorObject *self, visitproc visit, void *arg)
752 Py_VISIT(self->myerrno);
753 Py_VISIT(self->strerror);
754 Py_VISIT(self->filename);
755 Py_VISIT(self->winerror);
756 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
759 static int
760 WindowsError_init(PyWindowsErrorObject *self, PyObject *args, PyObject *kwds)
762 PyObject *o_errcode = NULL;
763 long errcode;
764 long posix_errno;
766 if (EnvironmentError_init((PyEnvironmentErrorObject *)self, args, kwds)
767 == -1)
768 return -1;
770 if (self->myerrno == NULL)
771 return 0;
773 /* Set errno to the POSIX errno, and winerror to the Win32
774 error code. */
775 errcode = PyLong_AsLong(self->myerrno);
776 if (errcode == -1 && PyErr_Occurred())
777 return -1;
778 posix_errno = winerror_to_errno(errcode);
780 Py_CLEAR(self->winerror);
781 self->winerror = self->myerrno;
783 o_errcode = PyLong_FromLong(posix_errno);
784 if (!o_errcode)
785 return -1;
787 self->myerrno = o_errcode;
789 return 0;
793 static PyObject *
794 WindowsError_str(PyWindowsErrorObject *self)
796 if (self->filename)
797 return PyUnicode_FromFormat("[Error %S] %S: %R",
798 self->winerror ? self->winerror: Py_None,
799 self->strerror ? self->strerror: Py_None,
800 self->filename);
801 else if (self->winerror && self->strerror)
802 return PyUnicode_FromFormat("[Error %S] %S",
803 self->winerror ? self->winerror: Py_None,
804 self->strerror ? self->strerror: Py_None);
805 else
806 return EnvironmentError_str((PyEnvironmentErrorObject *)self);
809 static PyMemberDef WindowsError_members[] = {
810 {"errno", T_OBJECT, offsetof(PyWindowsErrorObject, myerrno), 0,
811 PyDoc_STR("POSIX exception code")},
812 {"strerror", T_OBJECT, offsetof(PyWindowsErrorObject, strerror), 0,
813 PyDoc_STR("exception strerror")},
814 {"filename", T_OBJECT, offsetof(PyWindowsErrorObject, filename), 0,
815 PyDoc_STR("exception filename")},
816 {"winerror", T_OBJECT, offsetof(PyWindowsErrorObject, winerror), 0,
817 PyDoc_STR("Win32 exception code")},
818 {NULL} /* Sentinel */
821 ComplexExtendsException(PyExc_OSError, WindowsError, WindowsError,
822 WindowsError_dealloc, 0, WindowsError_members,
823 WindowsError_str, "MS-Windows OS system call failed.");
825 #endif /* MS_WINDOWS */
829 * VMSError extends OSError (I think)
831 #ifdef __VMS
832 MiddlingExtendsException(PyExc_OSError, VMSError, EnvironmentError,
833 "OpenVMS OS system call failed.");
834 #endif
838 * EOFError extends Exception
840 SimpleExtendsException(PyExc_Exception, EOFError,
841 "Read beyond end of file.");
845 * RuntimeError extends Exception
847 SimpleExtendsException(PyExc_Exception, RuntimeError,
848 "Unspecified run-time error.");
852 * NotImplementedError extends RuntimeError
854 SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
855 "Method or function hasn't been implemented yet.");
858 * NameError extends Exception
860 SimpleExtendsException(PyExc_Exception, NameError,
861 "Name not found globally.");
864 * UnboundLocalError extends NameError
866 SimpleExtendsException(PyExc_NameError, UnboundLocalError,
867 "Local name referenced but not bound to a value.");
870 * AttributeError extends Exception
872 SimpleExtendsException(PyExc_Exception, AttributeError,
873 "Attribute not found.");
877 * SyntaxError extends Exception
880 static int
881 SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
883 PyObject *info = NULL;
884 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
886 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
887 return -1;
889 if (lenargs >= 1) {
890 Py_CLEAR(self->msg);
891 self->msg = PyTuple_GET_ITEM(args, 0);
892 Py_INCREF(self->msg);
894 if (lenargs == 2) {
895 info = PyTuple_GET_ITEM(args, 1);
896 info = PySequence_Tuple(info);
897 if (!info) return -1;
899 if (PyTuple_GET_SIZE(info) != 4) {
900 /* not a very good error message, but it's what Python 2.4 gives */
901 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
902 Py_DECREF(info);
903 return -1;
906 Py_CLEAR(self->filename);
907 self->filename = PyTuple_GET_ITEM(info, 0);
908 Py_INCREF(self->filename);
910 Py_CLEAR(self->lineno);
911 self->lineno = PyTuple_GET_ITEM(info, 1);
912 Py_INCREF(self->lineno);
914 Py_CLEAR(self->offset);
915 self->offset = PyTuple_GET_ITEM(info, 2);
916 Py_INCREF(self->offset);
918 Py_CLEAR(self->text);
919 self->text = PyTuple_GET_ITEM(info, 3);
920 Py_INCREF(self->text);
922 Py_DECREF(info);
924 return 0;
927 static int
928 SyntaxError_clear(PySyntaxErrorObject *self)
930 Py_CLEAR(self->msg);
931 Py_CLEAR(self->filename);
932 Py_CLEAR(self->lineno);
933 Py_CLEAR(self->offset);
934 Py_CLEAR(self->text);
935 Py_CLEAR(self->print_file_and_line);
936 return BaseException_clear((PyBaseExceptionObject *)self);
939 static void
940 SyntaxError_dealloc(PySyntaxErrorObject *self)
942 _PyObject_GC_UNTRACK(self);
943 SyntaxError_clear(self);
944 Py_TYPE(self)->tp_free((PyObject *)self);
947 static int
948 SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
950 Py_VISIT(self->msg);
951 Py_VISIT(self->filename);
952 Py_VISIT(self->lineno);
953 Py_VISIT(self->offset);
954 Py_VISIT(self->text);
955 Py_VISIT(self->print_file_and_line);
956 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
959 /* This is called "my_basename" instead of just "basename" to avoid name
960 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
961 defined, and Python does define that. */
962 static char *
963 my_basename(char *name)
965 char *cp = name;
966 char *result = name;
968 if (name == NULL)
969 return "???";
970 while (*cp != '\0') {
971 if (*cp == SEP)
972 result = cp + 1;
973 ++cp;
975 return result;
979 static PyObject *
980 SyntaxError_str(PySyntaxErrorObject *self)
982 int have_lineno = 0;
983 char *filename = 0;
984 /* Below, we always ignore overflow errors, just printing -1.
985 Still, we cannot allow an OverflowError to be raised, so
986 we need to call PyLong_AsLongAndOverflow. */
987 int overflow;
989 /* XXX -- do all the additional formatting with filename and
990 lineno here */
992 if (self->filename && PyUnicode_Check(self->filename)) {
993 filename = _PyUnicode_AsString(self->filename);
995 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
997 if (!filename && !have_lineno)
998 return PyObject_Str(self->msg ? self->msg : Py_None);
1000 if (filename && have_lineno)
1001 return PyUnicode_FromFormat("%S (%s, line %ld)",
1002 self->msg ? self->msg : Py_None,
1003 my_basename(filename),
1004 PyLong_AsLongAndOverflow(self->lineno, &overflow));
1005 else if (filename)
1006 return PyUnicode_FromFormat("%S (%s)",
1007 self->msg ? self->msg : Py_None,
1008 my_basename(filename));
1009 else /* only have_lineno */
1010 return PyUnicode_FromFormat("%S (line %ld)",
1011 self->msg ? self->msg : Py_None,
1012 PyLong_AsLongAndOverflow(self->lineno, &overflow));
1015 static PyMemberDef SyntaxError_members[] = {
1016 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1017 PyDoc_STR("exception msg")},
1018 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1019 PyDoc_STR("exception filename")},
1020 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1021 PyDoc_STR("exception lineno")},
1022 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1023 PyDoc_STR("exception offset")},
1024 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1025 PyDoc_STR("exception text")},
1026 {"print_file_and_line", T_OBJECT,
1027 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1028 PyDoc_STR("exception print_file_and_line")},
1029 {NULL} /* Sentinel */
1032 ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
1033 SyntaxError_dealloc, 0, SyntaxError_members,
1034 SyntaxError_str, "Invalid syntax.");
1038 * IndentationError extends SyntaxError
1040 MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1041 "Improper indentation.");
1045 * TabError extends IndentationError
1047 MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1048 "Improper mixture of spaces and tabs.");
1052 * LookupError extends Exception
1054 SimpleExtendsException(PyExc_Exception, LookupError,
1055 "Base class for lookup errors.");
1059 * IndexError extends LookupError
1061 SimpleExtendsException(PyExc_LookupError, IndexError,
1062 "Sequence index out of range.");
1066 * KeyError extends LookupError
1068 static PyObject *
1069 KeyError_str(PyBaseExceptionObject *self)
1071 /* If args is a tuple of exactly one item, apply repr to args[0].
1072 This is done so that e.g. the exception raised by {}[''] prints
1073 KeyError: ''
1074 rather than the confusing
1075 KeyError
1076 alone. The downside is that if KeyError is raised with an explanatory
1077 string, that string will be displayed in quotes. Too bad.
1078 If args is anything else, use the default BaseException__str__().
1080 if (PyTuple_GET_SIZE(self->args) == 1) {
1081 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
1083 return BaseException_str(self);
1086 ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
1087 0, 0, 0, KeyError_str, "Mapping key not found.");
1091 * ValueError extends Exception
1093 SimpleExtendsException(PyExc_Exception, ValueError,
1094 "Inappropriate argument value (of correct type).");
1097 * UnicodeError extends ValueError
1100 SimpleExtendsException(PyExc_ValueError, UnicodeError,
1101 "Unicode related error.");
1103 static PyObject *
1104 get_string(PyObject *attr, const char *name)
1106 if (!attr) {
1107 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1108 return NULL;
1111 if (!PyBytes_Check(attr)) {
1112 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1113 return NULL;
1115 Py_INCREF(attr);
1116 return attr;
1119 static PyObject *
1120 get_unicode(PyObject *attr, const char *name)
1122 if (!attr) {
1123 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1124 return NULL;
1127 if (!PyUnicode_Check(attr)) {
1128 PyErr_Format(PyExc_TypeError,
1129 "%.200s attribute must be unicode", name);
1130 return NULL;
1132 Py_INCREF(attr);
1133 return attr;
1136 static int
1137 set_unicodefromstring(PyObject **attr, const char *value)
1139 PyObject *obj = PyUnicode_FromString(value);
1140 if (!obj)
1141 return -1;
1142 Py_CLEAR(*attr);
1143 *attr = obj;
1144 return 0;
1147 PyObject *
1148 PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1150 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
1153 PyObject *
1154 PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1156 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
1159 PyObject *
1160 PyUnicodeEncodeError_GetObject(PyObject *exc)
1162 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1165 PyObject *
1166 PyUnicodeDecodeError_GetObject(PyObject *exc)
1168 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
1171 PyObject *
1172 PyUnicodeTranslateError_GetObject(PyObject *exc)
1174 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1178 PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1180 Py_ssize_t size;
1181 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1182 "object");
1183 if (!obj)
1184 return -1;
1185 *start = ((PyUnicodeErrorObject *)exc)->start;
1186 size = PyUnicode_GET_SIZE(obj);
1187 if (*start<0)
1188 *start = 0; /*XXX check for values <0*/
1189 if (*start>=size)
1190 *start = size-1;
1191 Py_DECREF(obj);
1192 return 0;
1197 PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1199 Py_ssize_t size;
1200 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
1201 if (!obj)
1202 return -1;
1203 size = PyBytes_GET_SIZE(obj);
1204 *start = ((PyUnicodeErrorObject *)exc)->start;
1205 if (*start<0)
1206 *start = 0;
1207 if (*start>=size)
1208 *start = size-1;
1209 Py_DECREF(obj);
1210 return 0;
1215 PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1217 return PyUnicodeEncodeError_GetStart(exc, start);
1222 PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1224 ((PyUnicodeErrorObject *)exc)->start = start;
1225 return 0;
1230 PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1232 ((PyUnicodeErrorObject *)exc)->start = start;
1233 return 0;
1238 PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1240 ((PyUnicodeErrorObject *)exc)->start = start;
1241 return 0;
1246 PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1248 Py_ssize_t size;
1249 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1250 "object");
1251 if (!obj)
1252 return -1;
1253 *end = ((PyUnicodeErrorObject *)exc)->end;
1254 size = PyUnicode_GET_SIZE(obj);
1255 if (*end<1)
1256 *end = 1;
1257 if (*end>size)
1258 *end = size;
1259 Py_DECREF(obj);
1260 return 0;
1265 PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1267 Py_ssize_t size;
1268 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
1269 if (!obj)
1270 return -1;
1271 size = PyBytes_GET_SIZE(obj);
1272 *end = ((PyUnicodeErrorObject *)exc)->end;
1273 if (*end<1)
1274 *end = 1;
1275 if (*end>size)
1276 *end = size;
1277 Py_DECREF(obj);
1278 return 0;
1283 PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1285 return PyUnicodeEncodeError_GetEnd(exc, start);
1290 PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1292 ((PyUnicodeErrorObject *)exc)->end = end;
1293 return 0;
1298 PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1300 ((PyUnicodeErrorObject *)exc)->end = end;
1301 return 0;
1306 PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1308 ((PyUnicodeErrorObject *)exc)->end = end;
1309 return 0;
1312 PyObject *
1313 PyUnicodeEncodeError_GetReason(PyObject *exc)
1315 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
1319 PyObject *
1320 PyUnicodeDecodeError_GetReason(PyObject *exc)
1322 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
1326 PyObject *
1327 PyUnicodeTranslateError_GetReason(PyObject *exc)
1329 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
1334 PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1336 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1337 reason);
1342 PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1344 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1345 reason);
1350 PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1352 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1353 reason);
1357 static int
1358 UnicodeError_clear(PyUnicodeErrorObject *self)
1360 Py_CLEAR(self->encoding);
1361 Py_CLEAR(self->object);
1362 Py_CLEAR(self->reason);
1363 return BaseException_clear((PyBaseExceptionObject *)self);
1366 static void
1367 UnicodeError_dealloc(PyUnicodeErrorObject *self)
1369 _PyObject_GC_UNTRACK(self);
1370 UnicodeError_clear(self);
1371 Py_TYPE(self)->tp_free((PyObject *)self);
1374 static int
1375 UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1377 Py_VISIT(self->encoding);
1378 Py_VISIT(self->object);
1379 Py_VISIT(self->reason);
1380 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1383 static PyMemberDef UnicodeError_members[] = {
1384 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1385 PyDoc_STR("exception encoding")},
1386 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1387 PyDoc_STR("exception object")},
1388 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
1389 PyDoc_STR("exception start")},
1390 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
1391 PyDoc_STR("exception end")},
1392 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1393 PyDoc_STR("exception reason")},
1394 {NULL} /* Sentinel */
1399 * UnicodeEncodeError extends UnicodeError
1402 static int
1403 UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1405 PyUnicodeErrorObject *err;
1407 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1408 return -1;
1410 err = (PyUnicodeErrorObject *)self;
1412 Py_CLEAR(err->encoding);
1413 Py_CLEAR(err->object);
1414 Py_CLEAR(err->reason);
1416 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1417 &PyUnicode_Type, &err->encoding,
1418 &PyUnicode_Type, &err->object,
1419 &err->start,
1420 &err->end,
1421 &PyUnicode_Type, &err->reason)) {
1422 err->encoding = err->object = err->reason = NULL;
1423 return -1;
1426 Py_INCREF(err->encoding);
1427 Py_INCREF(err->object);
1428 Py_INCREF(err->reason);
1430 return 0;
1433 static PyObject *
1434 UnicodeEncodeError_str(PyObject *self)
1436 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
1437 PyObject *result = NULL;
1438 PyObject *reason_str = NULL;
1439 PyObject *encoding_str = NULL;
1441 /* Get reason and encoding as strings, which they might not be if
1442 they've been modified after we were contructed. */
1443 reason_str = PyObject_Str(uself->reason);
1444 if (reason_str == NULL)
1445 goto done;
1446 encoding_str = PyObject_Str(uself->encoding);
1447 if (encoding_str == NULL)
1448 goto done;
1450 if (uself->start < PyUnicode_GET_SIZE(uself->object) && uself->end == uself->start+1) {
1451 int badchar = (int)PyUnicode_AS_UNICODE(uself->object)[uself->start];
1452 const char *fmt;
1453 if (badchar <= 0xff)
1454 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
1455 else if (badchar <= 0xffff)
1456 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
1457 else
1458 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
1459 result = PyUnicode_FromFormat(
1460 fmt,
1461 encoding_str,
1462 badchar,
1463 uself->start,
1464 reason_str);
1466 else {
1467 result = PyUnicode_FromFormat(
1468 "'%U' codec can't encode characters in position %zd-%zd: %U",
1469 encoding_str,
1470 uself->start,
1471 uself->end-1,
1472 reason_str);
1474 done:
1475 Py_XDECREF(reason_str);
1476 Py_XDECREF(encoding_str);
1477 return result;
1480 static PyTypeObject _PyExc_UnicodeEncodeError = {
1481 PyVarObject_HEAD_INIT(NULL, 0)
1482 "UnicodeEncodeError",
1483 sizeof(PyUnicodeErrorObject), 0,
1484 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1485 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1486 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1487 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1488 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
1489 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
1490 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
1492 PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1494 PyObject *
1495 PyUnicodeEncodeError_Create(
1496 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1497 Py_ssize_t start, Py_ssize_t end, const char *reason)
1499 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "Uu#nnU",
1500 encoding, object, length, start, end, reason);
1505 * UnicodeDecodeError extends UnicodeError
1508 static int
1509 UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1511 PyUnicodeErrorObject *ude;
1512 const char *data;
1513 Py_ssize_t size;
1515 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1516 return -1;
1518 ude = (PyUnicodeErrorObject *)self;
1520 Py_CLEAR(ude->encoding);
1521 Py_CLEAR(ude->object);
1522 Py_CLEAR(ude->reason);
1524 if (!PyArg_ParseTuple(args, "O!OnnO!",
1525 &PyUnicode_Type, &ude->encoding,
1526 &ude->object,
1527 &ude->start,
1528 &ude->end,
1529 &PyUnicode_Type, &ude->reason)) {
1530 ude->encoding = ude->object = ude->reason = NULL;
1531 return -1;
1534 if (!PyBytes_Check(ude->object)) {
1535 if (PyObject_AsReadBuffer(ude->object, (const void **)&data, &size)) {
1536 ude->encoding = ude->object = ude->reason = NULL;
1537 return -1;
1539 ude->object = PyBytes_FromStringAndSize(data, size);
1541 else {
1542 Py_INCREF(ude->object);
1545 Py_INCREF(ude->encoding);
1546 Py_INCREF(ude->reason);
1548 return 0;
1551 static PyObject *
1552 UnicodeDecodeError_str(PyObject *self)
1554 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
1555 PyObject *result = NULL;
1556 PyObject *reason_str = NULL;
1557 PyObject *encoding_str = NULL;
1559 /* Get reason and encoding as strings, which they might not be if
1560 they've been modified after we were contructed. */
1561 reason_str = PyObject_Str(uself->reason);
1562 if (reason_str == NULL)
1563 goto done;
1564 encoding_str = PyObject_Str(uself->encoding);
1565 if (encoding_str == NULL)
1566 goto done;
1568 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
1569 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
1570 result = PyUnicode_FromFormat(
1571 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
1572 encoding_str,
1573 byte,
1574 uself->start,
1575 reason_str);
1577 else {
1578 result = PyUnicode_FromFormat(
1579 "'%U' codec can't decode bytes in position %zd-%zd: %U",
1580 encoding_str,
1581 uself->start,
1582 uself->end-1,
1583 reason_str
1586 done:
1587 Py_XDECREF(reason_str);
1588 Py_XDECREF(encoding_str);
1589 return result;
1592 static PyTypeObject _PyExc_UnicodeDecodeError = {
1593 PyVarObject_HEAD_INIT(NULL, 0)
1594 "UnicodeDecodeError",
1595 sizeof(PyUnicodeErrorObject), 0,
1596 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1597 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
1598 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1599 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
1600 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
1601 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
1602 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
1604 PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
1606 PyObject *
1607 PyUnicodeDecodeError_Create(
1608 const char *encoding, const char *object, Py_ssize_t length,
1609 Py_ssize_t start, Py_ssize_t end, const char *reason)
1611 assert(length < INT_MAX);
1612 assert(start < INT_MAX);
1613 assert(end < INT_MAX);
1614 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "Uy#nnU",
1615 encoding, object, length, start, end, reason);
1620 * UnicodeTranslateError extends UnicodeError
1623 static int
1624 UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
1625 PyObject *kwds)
1627 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1628 return -1;
1630 Py_CLEAR(self->object);
1631 Py_CLEAR(self->reason);
1633 if (!PyArg_ParseTuple(args, "O!nnO!",
1634 &PyUnicode_Type, &self->object,
1635 &self->start,
1636 &self->end,
1637 &PyUnicode_Type, &self->reason)) {
1638 self->object = self->reason = NULL;
1639 return -1;
1642 Py_INCREF(self->object);
1643 Py_INCREF(self->reason);
1645 return 0;
1649 static PyObject *
1650 UnicodeTranslateError_str(PyObject *self)
1652 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
1653 PyObject *result = NULL;
1654 PyObject *reason_str = NULL;
1656 /* Get reason as a string, which it might not be if it's been
1657 modified after we were contructed. */
1658 reason_str = PyObject_Str(uself->reason);
1659 if (reason_str == NULL)
1660 goto done;
1662 if (uself->start < PyUnicode_GET_SIZE(uself->object) && uself->end == uself->start+1) {
1663 int badchar = (int)PyUnicode_AS_UNICODE(uself->object)[uself->start];
1664 const char *fmt;
1665 if (badchar <= 0xff)
1666 fmt = "can't translate character '\\x%02x' in position %zd: %U";
1667 else if (badchar <= 0xffff)
1668 fmt = "can't translate character '\\u%04x' in position %zd: %U";
1669 else
1670 fmt = "can't translate character '\\U%08x' in position %zd: %U";
1671 result = PyUnicode_FromFormat(
1672 fmt,
1673 badchar,
1674 uself->start,
1675 reason_str
1677 } else {
1678 result = PyUnicode_FromFormat(
1679 "can't translate characters in position %zd-%zd: %U",
1680 uself->start,
1681 uself->end-1,
1682 reason_str
1685 done:
1686 Py_XDECREF(reason_str);
1687 return result;
1690 static PyTypeObject _PyExc_UnicodeTranslateError = {
1691 PyVarObject_HEAD_INIT(NULL, 0)
1692 "UnicodeTranslateError",
1693 sizeof(PyUnicodeErrorObject), 0,
1694 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1695 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
1696 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1697 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
1698 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
1699 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
1700 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
1702 PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
1704 PyObject *
1705 PyUnicodeTranslateError_Create(
1706 const Py_UNICODE *object, Py_ssize_t length,
1707 Py_ssize_t start, Py_ssize_t end, const char *reason)
1709 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
1710 object, length, start, end, reason);
1715 * AssertionError extends Exception
1717 SimpleExtendsException(PyExc_Exception, AssertionError,
1718 "Assertion failed.");
1722 * ArithmeticError extends Exception
1724 SimpleExtendsException(PyExc_Exception, ArithmeticError,
1725 "Base class for arithmetic errors.");
1729 * FloatingPointError extends ArithmeticError
1731 SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
1732 "Floating point operation failed.");
1736 * OverflowError extends ArithmeticError
1738 SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
1739 "Result too large to be represented.");
1743 * ZeroDivisionError extends ArithmeticError
1745 SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
1746 "Second argument to a division or modulo operation was zero.");
1750 * SystemError extends Exception
1752 SimpleExtendsException(PyExc_Exception, SystemError,
1753 "Internal error in the Python interpreter.\n"
1754 "\n"
1755 "Please report this to the Python maintainer, along with the traceback,\n"
1756 "the Python version, and the hardware/OS platform and version.");
1760 * ReferenceError extends Exception
1762 SimpleExtendsException(PyExc_Exception, ReferenceError,
1763 "Weak ref proxy used after referent went away.");
1767 * MemoryError extends Exception
1769 SimpleExtendsException(PyExc_Exception, MemoryError, "Out of memory.");
1772 * BufferError extends Exception
1774 SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
1777 /* Warning category docstrings */
1780 * Warning extends Exception
1782 SimpleExtendsException(PyExc_Exception, Warning,
1783 "Base class for warning categories.");
1787 * UserWarning extends Warning
1789 SimpleExtendsException(PyExc_Warning, UserWarning,
1790 "Base class for warnings generated by user code.");
1794 * DeprecationWarning extends Warning
1796 SimpleExtendsException(PyExc_Warning, DeprecationWarning,
1797 "Base class for warnings about deprecated features.");
1801 * PendingDeprecationWarning extends Warning
1803 SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
1804 "Base class for warnings about features which will be deprecated\n"
1805 "in the future.");
1809 * SyntaxWarning extends Warning
1811 SimpleExtendsException(PyExc_Warning, SyntaxWarning,
1812 "Base class for warnings about dubious syntax.");
1816 * RuntimeWarning extends Warning
1818 SimpleExtendsException(PyExc_Warning, RuntimeWarning,
1819 "Base class for warnings about dubious runtime behavior.");
1823 * FutureWarning extends Warning
1825 SimpleExtendsException(PyExc_Warning, FutureWarning,
1826 "Base class for warnings about constructs that will change semantically\n"
1827 "in the future.");
1831 * ImportWarning extends Warning
1833 SimpleExtendsException(PyExc_Warning, ImportWarning,
1834 "Base class for warnings about probable mistakes in module imports");
1838 * UnicodeWarning extends Warning
1840 SimpleExtendsException(PyExc_Warning, UnicodeWarning,
1841 "Base class for warnings about Unicode related problems, mostly\n"
1842 "related to conversion problems.");
1845 * BytesWarning extends Warning
1847 SimpleExtendsException(PyExc_Warning, BytesWarning,
1848 "Base class for warnings about bytes and buffer related problems, mostly\n"
1849 "related to conversion from str or comparing to str.");
1853 /* Pre-computed MemoryError instance. Best to create this as early as
1854 * possible and not wait until a MemoryError is actually raised!
1856 PyObject *PyExc_MemoryErrorInst=NULL;
1858 /* Pre-computed RuntimeError instance for when recursion depth is reached.
1859 Meant to be used when normalizing the exception for exceeding the recursion
1860 depth will cause its own infinite recursion.
1862 PyObject *PyExc_RecursionErrorInst = NULL;
1864 #define PRE_INIT(TYPE) if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
1865 Py_FatalError("exceptions bootstrapping error.");
1867 #define POST_INIT(TYPE) Py_INCREF(PyExc_ ## TYPE); \
1868 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
1869 Py_FatalError("Module dictionary insertion problem.");
1872 void
1873 _PyExc_Init(void)
1875 PyObject *bltinmod, *bdict;
1877 PRE_INIT(BaseException)
1878 PRE_INIT(Exception)
1879 PRE_INIT(TypeError)
1880 PRE_INIT(StopIteration)
1881 PRE_INIT(GeneratorExit)
1882 PRE_INIT(SystemExit)
1883 PRE_INIT(KeyboardInterrupt)
1884 PRE_INIT(ImportError)
1885 PRE_INIT(EnvironmentError)
1886 PRE_INIT(IOError)
1887 PRE_INIT(OSError)
1888 #ifdef MS_WINDOWS
1889 PRE_INIT(WindowsError)
1890 #endif
1891 #ifdef __VMS
1892 PRE_INIT(VMSError)
1893 #endif
1894 PRE_INIT(EOFError)
1895 PRE_INIT(RuntimeError)
1896 PRE_INIT(NotImplementedError)
1897 PRE_INIT(NameError)
1898 PRE_INIT(UnboundLocalError)
1899 PRE_INIT(AttributeError)
1900 PRE_INIT(SyntaxError)
1901 PRE_INIT(IndentationError)
1902 PRE_INIT(TabError)
1903 PRE_INIT(LookupError)
1904 PRE_INIT(IndexError)
1905 PRE_INIT(KeyError)
1906 PRE_INIT(ValueError)
1907 PRE_INIT(UnicodeError)
1908 PRE_INIT(UnicodeEncodeError)
1909 PRE_INIT(UnicodeDecodeError)
1910 PRE_INIT(UnicodeTranslateError)
1911 PRE_INIT(AssertionError)
1912 PRE_INIT(ArithmeticError)
1913 PRE_INIT(FloatingPointError)
1914 PRE_INIT(OverflowError)
1915 PRE_INIT(ZeroDivisionError)
1916 PRE_INIT(SystemError)
1917 PRE_INIT(ReferenceError)
1918 PRE_INIT(BufferError)
1919 PRE_INIT(MemoryError)
1920 PRE_INIT(BufferError)
1921 PRE_INIT(Warning)
1922 PRE_INIT(UserWarning)
1923 PRE_INIT(DeprecationWarning)
1924 PRE_INIT(PendingDeprecationWarning)
1925 PRE_INIT(SyntaxWarning)
1926 PRE_INIT(RuntimeWarning)
1927 PRE_INIT(FutureWarning)
1928 PRE_INIT(ImportWarning)
1929 PRE_INIT(UnicodeWarning)
1930 PRE_INIT(BytesWarning)
1932 bltinmod = PyImport_ImportModule("builtins");
1933 if (bltinmod == NULL)
1934 Py_FatalError("exceptions bootstrapping error.");
1935 bdict = PyModule_GetDict(bltinmod);
1936 if (bdict == NULL)
1937 Py_FatalError("exceptions bootstrapping error.");
1939 POST_INIT(BaseException)
1940 POST_INIT(Exception)
1941 POST_INIT(TypeError)
1942 POST_INIT(StopIteration)
1943 POST_INIT(GeneratorExit)
1944 POST_INIT(SystemExit)
1945 POST_INIT(KeyboardInterrupt)
1946 POST_INIT(ImportError)
1947 POST_INIT(EnvironmentError)
1948 POST_INIT(IOError)
1949 POST_INIT(OSError)
1950 #ifdef MS_WINDOWS
1951 POST_INIT(WindowsError)
1952 #endif
1953 #ifdef __VMS
1954 POST_INIT(VMSError)
1955 #endif
1956 POST_INIT(EOFError)
1957 POST_INIT(RuntimeError)
1958 POST_INIT(NotImplementedError)
1959 POST_INIT(NameError)
1960 POST_INIT(UnboundLocalError)
1961 POST_INIT(AttributeError)
1962 POST_INIT(SyntaxError)
1963 POST_INIT(IndentationError)
1964 POST_INIT(TabError)
1965 POST_INIT(LookupError)
1966 POST_INIT(IndexError)
1967 POST_INIT(KeyError)
1968 POST_INIT(ValueError)
1969 POST_INIT(UnicodeError)
1970 POST_INIT(UnicodeEncodeError)
1971 POST_INIT(UnicodeDecodeError)
1972 POST_INIT(UnicodeTranslateError)
1973 POST_INIT(AssertionError)
1974 POST_INIT(ArithmeticError)
1975 POST_INIT(FloatingPointError)
1976 POST_INIT(OverflowError)
1977 POST_INIT(ZeroDivisionError)
1978 POST_INIT(SystemError)
1979 POST_INIT(ReferenceError)
1980 POST_INIT(BufferError)
1981 POST_INIT(MemoryError)
1982 POST_INIT(BufferError)
1983 POST_INIT(Warning)
1984 POST_INIT(UserWarning)
1985 POST_INIT(DeprecationWarning)
1986 POST_INIT(PendingDeprecationWarning)
1987 POST_INIT(SyntaxWarning)
1988 POST_INIT(RuntimeWarning)
1989 POST_INIT(FutureWarning)
1990 POST_INIT(ImportWarning)
1991 POST_INIT(UnicodeWarning)
1992 POST_INIT(BytesWarning)
1994 PyExc_MemoryErrorInst = BaseException_new(&_PyExc_MemoryError, NULL, NULL);
1995 if (!PyExc_MemoryErrorInst)
1996 Py_FatalError("Cannot pre-allocate MemoryError instance");
1998 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL);
1999 if (!PyExc_RecursionErrorInst)
2000 Py_FatalError("Cannot pre-allocate RuntimeError instance for "
2001 "recursion errors");
2002 else {
2003 PyBaseExceptionObject *err_inst =
2004 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2005 PyObject *args_tuple;
2006 PyObject *exc_message;
2007 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2008 if (!exc_message)
2009 Py_FatalError("cannot allocate argument for RuntimeError "
2010 "pre-allocation");
2011 args_tuple = PyTuple_Pack(1, exc_message);
2012 if (!args_tuple)
2013 Py_FatalError("cannot allocate tuple for RuntimeError "
2014 "pre-allocation");
2015 Py_DECREF(exc_message);
2016 if (BaseException_init(err_inst, args_tuple, NULL))
2017 Py_FatalError("init of pre-allocated RuntimeError failed");
2018 Py_DECREF(args_tuple);
2021 Py_DECREF(bltinmod);
2024 void
2025 _PyExc_Fini(void)
2027 Py_XDECREF(PyExc_MemoryErrorInst);
2028 PyExc_MemoryErrorInst = NULL;