Catch situations where currentframe() returns None. See SF patch #1447410, this is...
[python.git] / Python / exceptions.c
blobb146c971b9c87a4c77f9dc261ea19c5fa6288233
1 /* This module provides the suite of standard class-based exceptions for
2 * Python's builtin module. This is a complete C implementation of what,
3 * in Python 1.5.2, was contained in the exceptions.py module. The problem
4 * there was that if exceptions.py could not be imported for some reason,
5 * the entire interpreter would abort.
7 * By moving the exceptions into C and statically linking, we can guarantee
8 * that the standard exceptions will always be available.
11 * written by Fredrik Lundh
12 * modifications, additions, cleanups, and proofreading by Barry Warsaw
14 * Copyright (c) 1998-2000 by Secret Labs AB. All rights reserved.
17 #include "Python.h"
18 #include "osdefs.h"
20 /* Caution: MS Visual C++ 6 errors if a single string literal exceeds
21 * 2Kb. So the module docstring has been broken roughly in half, using
22 * compile-time literal concatenation.
25 /* NOTE: If the exception class hierarchy changes, don't forget to update
26 * Doc/lib/libexcs.tex!
29 PyDoc_STRVAR(module__doc__,
30 "Python's standard exception class hierarchy.\n\
31 \n\
32 Exceptions found here are defined both in the exceptions module and the \n\
33 built-in namespace. It is recommended that user-defined exceptions inherit \n\
34 from Exception. See the documentation for the exception inheritance hierarchy.\n\
37 /* keep string pieces "small" */
38 /* XXX(bcannon): exception hierarchy in Lib/test/exception_hierarchy.txt */
42 /* Helper function for populating a dictionary with method wrappers. */
43 static int
44 populate_methods(PyObject *klass, PyMethodDef *methods)
46 PyObject *module;
47 int status = -1;
49 if (!methods)
50 return 0;
52 module = PyString_FromString("exceptions");
53 if (!module)
54 return 0;
55 while (methods->ml_name) {
56 /* get a wrapper for the built-in function */
57 PyObject *func = PyCFunction_NewEx(methods, NULL, module);
58 PyObject *meth;
60 if (!func)
61 goto status;
63 /* turn the function into an unbound method */
64 if (!(meth = PyMethod_New(func, NULL, klass))) {
65 Py_DECREF(func);
66 goto status;
69 /* add method to dictionary */
70 status = PyObject_SetAttrString(klass, methods->ml_name, meth);
71 Py_DECREF(meth);
72 Py_DECREF(func);
74 /* stop now if an error occurred, otherwise do the next method */
75 if (status)
76 goto status;
78 methods++;
80 status = 0;
81 status:
82 Py_DECREF(module);
83 return status;
88 /* This function is used to create all subsequent exception classes. */
89 static int
90 make_class(PyObject **klass, PyObject *base,
91 char *name, PyMethodDef *methods,
92 char *docstr)
94 PyObject *dict = PyDict_New();
95 PyObject *str = NULL;
96 int status = -1;
98 if (!dict)
99 return -1;
101 /* If an error occurs from here on, goto finally instead of explicitly
102 * returning NULL.
105 if (docstr) {
106 if (!(str = PyString_FromString(docstr)))
107 goto finally;
108 if (PyDict_SetItemString(dict, "__doc__", str))
109 goto finally;
112 if (!(*klass = PyErr_NewException(name, base, dict)))
113 goto finally;
115 if (populate_methods(*klass, methods)) {
116 Py_DECREF(*klass);
117 *klass = NULL;
118 goto finally;
121 status = 0;
123 finally:
124 Py_XDECREF(dict);
125 Py_XDECREF(str);
126 return status;
130 /* Use this for *args signatures, otherwise just use PyArg_ParseTuple() */
131 static PyObject *
132 get_self(PyObject *args)
134 PyObject *self = PyTuple_GetItem(args, 0);
135 if (!self) {
136 /* Watch out for being called to early in the bootstrapping process */
137 if (PyExc_TypeError) {
138 PyErr_SetString(PyExc_TypeError,
139 "unbound method must be called with instance as first argument");
141 return NULL;
143 return self;
148 /* Notes on bootstrapping the exception classes.
150 * First thing we create is the base class for all exceptions, called
151 * appropriately BaseException. Creation of this class makes no
152 * assumptions about the existence of any other exception class -- except
153 * for TypeError, which can conditionally exist.
155 * Next, Exception is created since it is the common subclass for the rest of
156 * the needed exceptions for this bootstrapping to work. StandardError is
157 * created (which is quite simple) followed by
158 * TypeError, because the instantiation of other exceptions can potentially
159 * throw a TypeError. Once these exceptions are created, all the others
160 * can be created in any order. See the static exctable below for the
161 * explicit bootstrap order.
163 * All classes after BaseException can be created using PyErr_NewException().
166 PyDoc_STRVAR(BaseException__doc__, "Common base class for all exceptions");
169 Set args and message attributes.
171 Assumes self and args have already been set properly with set_self, etc.
173 static int
174 set_args_and_message(PyObject *self, PyObject *args)
176 PyObject *message_val;
177 Py_ssize_t args_len = PySequence_Length(args);
179 if (args_len < 0)
180 return 0;
182 /* set args */
183 if (PyObject_SetAttrString(self, "args", args) < 0)
184 return 0;
186 /* set message */
187 if (args_len == 1)
188 message_val = PySequence_GetItem(args, 0);
189 else
190 message_val = PyString_FromString("");
191 if (!message_val)
192 return 0;
194 if (PyObject_SetAttrString(self, "message", message_val) < 0) {
195 Py_DECREF(message_val);
196 return 0;
199 Py_DECREF(message_val);
200 return 1;
203 static PyObject *
204 BaseException__init__(PyObject *self, PyObject *args)
206 if (!(self = get_self(args)))
207 return NULL;
209 /* set args and message attribute */
210 args = PySequence_GetSlice(args, 1, PySequence_Length(args));
211 if (!args)
212 return NULL;
214 if (!set_args_and_message(self, args)) {
215 Py_DECREF(args);
216 return NULL;
219 Py_DECREF(args);
220 Py_RETURN_NONE;
224 static PyObject *
225 BaseException__str__(PyObject *self, PyObject *args)
227 PyObject *out;
229 if (!PyArg_ParseTuple(args, "O:__str__", &self))
230 return NULL;
232 args = PyObject_GetAttrString(self, "args");
233 if (!args)
234 return NULL;
236 switch (PySequence_Size(args)) {
237 case 0:
238 out = PyString_FromString("");
239 break;
240 case 1:
242 PyObject *tmp = PySequence_GetItem(args, 0);
243 if (tmp) {
244 out = PyObject_Str(tmp);
245 Py_DECREF(tmp);
247 else
248 out = NULL;
249 break;
251 case -1:
252 PyErr_Clear();
253 /* Fall through */
254 default:
255 out = PyObject_Str(args);
256 break;
259 Py_DECREF(args);
260 return out;
263 #ifdef Py_USING_UNICODE
264 static PyObject *
265 BaseException__unicode__(PyObject *self, PyObject *args)
267 Py_ssize_t args_len;
269 if (!PyArg_ParseTuple(args, "O:__unicode__", &self))
270 return NULL;
272 args = PyObject_GetAttrString(self, "args");
273 if (!args)
274 return NULL;
276 args_len = PySequence_Size(args);
277 if (args_len < 0) {
278 Py_DECREF(args);
279 return NULL;
282 if (args_len == 0) {
283 Py_DECREF(args);
284 return PyUnicode_FromUnicode(NULL, 0);
286 else if (args_len == 1) {
287 PyObject *temp = PySequence_GetItem(args, 0);
288 PyObject *unicode_obj;
290 if (!temp) {
291 Py_DECREF(args);
292 return NULL;
294 Py_DECREF(args);
295 unicode_obj = PyObject_Unicode(temp);
296 Py_DECREF(temp);
297 return unicode_obj;
299 else {
300 PyObject *unicode_obj = PyObject_Unicode(args);
302 Py_DECREF(args);
303 return unicode_obj;
306 #endif /* Py_USING_UNICODE */
308 static PyObject *
309 BaseException__repr__(PyObject *self, PyObject *args)
311 PyObject *args_attr;
312 Py_ssize_t args_len;
313 PyObject *repr_suffix;
314 PyObject *repr;
316 if (!PyArg_ParseTuple(args, "O:__repr__", &self))
317 return NULL;
319 args_attr = PyObject_GetAttrString(self, "args");
320 if (!args_attr)
321 return NULL;
323 args_len = PySequence_Length(args_attr);
324 if (args_len < 0) {
325 Py_DECREF(args_attr);
326 return NULL;
329 if (args_len == 0) {
330 Py_DECREF(args_attr);
331 repr_suffix = PyString_FromString("()");
332 if (!repr_suffix)
333 return NULL;
335 else {
336 PyObject *args_repr = PyObject_Repr(args_attr);
337 Py_DECREF(args_attr);
338 if (!args_repr)
339 return NULL;
341 repr_suffix = args_repr;
344 repr = PyString_FromString(self->ob_type->tp_name);
345 if (!repr) {
346 Py_DECREF(repr_suffix);
347 return NULL;
350 PyString_ConcatAndDel(&repr, repr_suffix);
351 return repr;
354 static PyObject *
355 BaseException__getitem__(PyObject *self, PyObject *args)
357 PyObject *out;
358 PyObject *index;
360 if (!PyArg_ParseTuple(args, "OO:__getitem__", &self, &index))
361 return NULL;
363 args = PyObject_GetAttrString(self, "args");
364 if (!args)
365 return NULL;
367 out = PyObject_GetItem(args, index);
368 Py_DECREF(args);
369 return out;
373 static PyMethodDef
374 BaseException_methods[] = {
375 /* methods for the BaseException class */
376 {"__getitem__", BaseException__getitem__, METH_VARARGS},
377 {"__repr__", BaseException__repr__, METH_VARARGS},
378 {"__str__", BaseException__str__, METH_VARARGS},
379 #ifdef Py_USING_UNICODE
380 {"__unicode__", BaseException__unicode__, METH_VARARGS},
381 #endif /* Py_USING_UNICODE */
382 {"__init__", BaseException__init__, METH_VARARGS},
383 {NULL, NULL }
387 static int
388 make_BaseException(char *modulename)
390 PyObject *dict = PyDict_New();
391 PyObject *str = NULL;
392 PyObject *name = NULL;
393 PyObject *emptytuple = NULL;
394 PyObject *argstuple = NULL;
395 int status = -1;
397 if (!dict)
398 return -1;
400 /* If an error occurs from here on, goto finally instead of explicitly
401 * returning NULL.
404 if (!(str = PyString_FromString(modulename)))
405 goto finally;
406 if (PyDict_SetItemString(dict, "__module__", str))
407 goto finally;
408 Py_DECREF(str);
410 if (!(str = PyString_FromString(BaseException__doc__)))
411 goto finally;
412 if (PyDict_SetItemString(dict, "__doc__", str))
413 goto finally;
415 if (!(name = PyString_FromString("BaseException")))
416 goto finally;
418 if (!(emptytuple = PyTuple_New(0)))
419 goto finally;
421 if (!(argstuple = PyTuple_Pack(3, name, emptytuple, dict)))
422 goto finally;
424 if (!(PyExc_BaseException = PyType_Type.tp_new(&PyType_Type, argstuple,
425 NULL)))
426 goto finally;
428 /* Now populate the dictionary with the method suite */
429 if (populate_methods(PyExc_BaseException, BaseException_methods))
430 /* Don't need to reclaim PyExc_BaseException here because that'll
431 * happen during interpreter shutdown.
433 goto finally;
435 status = 0;
437 finally:
438 Py_XDECREF(dict);
439 Py_XDECREF(str);
440 Py_XDECREF(name);
441 Py_XDECREF(emptytuple);
442 Py_XDECREF(argstuple);
443 return status;
448 PyDoc_STRVAR(Exception__doc__, "Common base class for all non-exit exceptions.");
450 PyDoc_STRVAR(StandardError__doc__,
451 "Base class for all standard Python exceptions that do not represent"
452 "interpreter exiting.");
454 PyDoc_STRVAR(TypeError__doc__, "Inappropriate argument type.");
456 PyDoc_STRVAR(StopIteration__doc__, "Signal the end from iterator.next().");
457 PyDoc_STRVAR(GeneratorExit__doc__, "Request that a generator exit.");
461 PyDoc_STRVAR(SystemExit__doc__, "Request to exit from the interpreter.");
464 static PyObject *
465 SystemExit__init__(PyObject *self, PyObject *args)
467 PyObject *code;
468 int status;
470 if (!(self = get_self(args)))
471 return NULL;
473 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
474 return NULL;
476 if (!set_args_and_message(self, args)) {
477 Py_DECREF(args);
478 return NULL;
481 /* set code attribute */
482 switch (PySequence_Size(args)) {
483 case 0:
484 Py_INCREF(Py_None);
485 code = Py_None;
486 break;
487 case 1:
488 code = PySequence_GetItem(args, 0);
489 break;
490 case -1:
491 PyErr_Clear();
492 /* Fall through */
493 default:
494 Py_INCREF(args);
495 code = args;
496 break;
499 status = PyObject_SetAttrString(self, "code", code);
500 Py_DECREF(code);
501 Py_DECREF(args);
502 if (status < 0)
503 return NULL;
505 Py_RETURN_NONE;
509 static PyMethodDef SystemExit_methods[] = {
510 { "__init__", SystemExit__init__, METH_VARARGS},
511 {NULL, NULL}
516 PyDoc_STRVAR(KeyboardInterrupt__doc__, "Program interrupted by user.");
518 PyDoc_STRVAR(ImportError__doc__,
519 "Import can't find module, or can't find name in module.");
523 PyDoc_STRVAR(EnvironmentError__doc__, "Base class for I/O related errors.");
526 static PyObject *
527 EnvironmentError__init__(PyObject *self, PyObject *args)
529 PyObject *item0 = NULL;
530 PyObject *item1 = NULL;
531 PyObject *item2 = NULL;
532 PyObject *subslice = NULL;
533 PyObject *rtnval = NULL;
535 if (!(self = get_self(args)))
536 return NULL;
538 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
539 return NULL;
541 if (!set_args_and_message(self, args)) {
542 Py_DECREF(args);
543 return NULL;
546 if (PyObject_SetAttrString(self, "errno", Py_None) ||
547 PyObject_SetAttrString(self, "strerror", Py_None) ||
548 PyObject_SetAttrString(self, "filename", Py_None))
550 goto finally;
553 switch (PySequence_Size(args)) {
554 case 3:
555 /* Where a function has a single filename, such as open() or some
556 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
557 * called, giving a third argument which is the filename. But, so
558 * that old code using in-place unpacking doesn't break, e.g.:
560 * except IOError, (errno, strerror):
562 * we hack args so that it only contains two items. This also
563 * means we need our own __str__() which prints out the filename
564 * when it was supplied.
566 item0 = PySequence_GetItem(args, 0);
567 item1 = PySequence_GetItem(args, 1);
568 item2 = PySequence_GetItem(args, 2);
569 if (!item0 || !item1 || !item2)
570 goto finally;
572 if (PyObject_SetAttrString(self, "errno", item0) ||
573 PyObject_SetAttrString(self, "strerror", item1) ||
574 PyObject_SetAttrString(self, "filename", item2))
576 goto finally;
579 subslice = PySequence_GetSlice(args, 0, 2);
580 if (!subslice || PyObject_SetAttrString(self, "args", subslice))
581 goto finally;
582 break;
584 case 2:
585 /* Used when PyErr_SetFromErrno() is called and no filename
586 * argument is given.
588 item0 = PySequence_GetItem(args, 0);
589 item1 = PySequence_GetItem(args, 1);
590 if (!item0 || !item1)
591 goto finally;
593 if (PyObject_SetAttrString(self, "errno", item0) ||
594 PyObject_SetAttrString(self, "strerror", item1))
596 goto finally;
598 break;
600 case -1:
601 PyErr_Clear();
602 break;
605 Py_INCREF(Py_None);
606 rtnval = Py_None;
608 finally:
609 Py_DECREF(args);
610 Py_XDECREF(item0);
611 Py_XDECREF(item1);
612 Py_XDECREF(item2);
613 Py_XDECREF(subslice);
614 return rtnval;
618 static PyObject *
619 EnvironmentError__str__(PyObject *self, PyObject *args)
621 PyObject *originalself = self;
622 PyObject *filename;
623 PyObject *serrno;
624 PyObject *strerror;
625 PyObject *rtnval = NULL;
627 if (!PyArg_ParseTuple(args, "O:__str__", &self))
628 return NULL;
630 filename = PyObject_GetAttrString(self, "filename");
631 serrno = PyObject_GetAttrString(self, "errno");
632 strerror = PyObject_GetAttrString(self, "strerror");
633 if (!filename || !serrno || !strerror)
634 goto finally;
636 if (filename != Py_None) {
637 PyObject *fmt = PyString_FromString("[Errno %s] %s: %s");
638 PyObject *repr = PyObject_Repr(filename);
639 PyObject *tuple = PyTuple_New(3);
641 if (!fmt || !repr || !tuple) {
642 Py_XDECREF(fmt);
643 Py_XDECREF(repr);
644 Py_XDECREF(tuple);
645 goto finally;
648 PyTuple_SET_ITEM(tuple, 0, serrno);
649 PyTuple_SET_ITEM(tuple, 1, strerror);
650 PyTuple_SET_ITEM(tuple, 2, repr);
652 rtnval = PyString_Format(fmt, tuple);
654 Py_DECREF(fmt);
655 Py_DECREF(tuple);
656 /* already freed because tuple owned only reference */
657 serrno = NULL;
658 strerror = NULL;
660 else if (PyObject_IsTrue(serrno) && PyObject_IsTrue(strerror)) {
661 PyObject *fmt = PyString_FromString("[Errno %s] %s");
662 PyObject *tuple = PyTuple_New(2);
664 if (!fmt || !tuple) {
665 Py_XDECREF(fmt);
666 Py_XDECREF(tuple);
667 goto finally;
670 PyTuple_SET_ITEM(tuple, 0, serrno);
671 PyTuple_SET_ITEM(tuple, 1, strerror);
673 rtnval = PyString_Format(fmt, tuple);
675 Py_DECREF(fmt);
676 Py_DECREF(tuple);
677 /* already freed because tuple owned only reference */
678 serrno = NULL;
679 strerror = NULL;
681 else
682 /* The original Python code said:
684 * return StandardError.__str__(self)
686 * but there is no StandardError__str__() function; we happen to
687 * know that's just a pass through to BaseException__str__().
689 rtnval = BaseException__str__(originalself, args);
691 finally:
692 Py_XDECREF(filename);
693 Py_XDECREF(serrno);
694 Py_XDECREF(strerror);
695 return rtnval;
699 static
700 PyMethodDef EnvironmentError_methods[] = {
701 {"__init__", EnvironmentError__init__, METH_VARARGS},
702 {"__str__", EnvironmentError__str__, METH_VARARGS},
703 {NULL, NULL}
709 PyDoc_STRVAR(IOError__doc__, "I/O operation failed.");
711 PyDoc_STRVAR(OSError__doc__, "OS system call failed.");
713 #ifdef MS_WINDOWS
714 PyDoc_STRVAR(WindowsError__doc__, "MS-Windows OS system call failed.");
715 #endif /* MS_WINDOWS */
717 #ifdef __VMS
718 static char
719 VMSError__doc__[] = "OpenVMS OS system call failed.";
720 #endif
722 PyDoc_STRVAR(EOFError__doc__, "Read beyond end of file.");
724 PyDoc_STRVAR(RuntimeError__doc__, "Unspecified run-time error.");
726 PyDoc_STRVAR(NotImplementedError__doc__,
727 "Method or function hasn't been implemented yet.");
729 PyDoc_STRVAR(NameError__doc__, "Name not found globally.");
731 PyDoc_STRVAR(UnboundLocalError__doc__,
732 "Local name referenced but not bound to a value.");
734 PyDoc_STRVAR(AttributeError__doc__, "Attribute not found.");
738 PyDoc_STRVAR(SyntaxError__doc__, "Invalid syntax.");
741 static int
742 SyntaxError__classinit__(PyObject *klass)
744 int retval = 0;
745 PyObject *emptystring = PyString_FromString("");
747 /* Additional class-creation time initializations */
748 if (!emptystring ||
749 PyObject_SetAttrString(klass, "msg", emptystring) ||
750 PyObject_SetAttrString(klass, "filename", Py_None) ||
751 PyObject_SetAttrString(klass, "lineno", Py_None) ||
752 PyObject_SetAttrString(klass, "offset", Py_None) ||
753 PyObject_SetAttrString(klass, "text", Py_None) ||
754 PyObject_SetAttrString(klass, "print_file_and_line", Py_None))
756 retval = -1;
758 Py_XDECREF(emptystring);
759 return retval;
763 static PyObject *
764 SyntaxError__init__(PyObject *self, PyObject *args)
766 PyObject *rtnval = NULL;
767 Py_ssize_t lenargs;
769 if (!(self = get_self(args)))
770 return NULL;
772 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
773 return NULL;
775 if (!set_args_and_message(self, args)) {
776 Py_DECREF(args);
777 return NULL;
780 lenargs = PySequence_Size(args);
781 if (lenargs >= 1) {
782 PyObject *item0 = PySequence_GetItem(args, 0);
783 int status;
785 if (!item0)
786 goto finally;
787 status = PyObject_SetAttrString(self, "msg", item0);
788 Py_DECREF(item0);
789 if (status)
790 goto finally;
792 if (lenargs == 2) {
793 PyObject *info = PySequence_GetItem(args, 1);
794 PyObject *filename = NULL, *lineno = NULL;
795 PyObject *offset = NULL, *text = NULL;
796 int status = 1;
798 if (!info)
799 goto finally;
801 filename = PySequence_GetItem(info, 0);
802 if (filename != NULL) {
803 lineno = PySequence_GetItem(info, 1);
804 if (lineno != NULL) {
805 offset = PySequence_GetItem(info, 2);
806 if (offset != NULL) {
807 text = PySequence_GetItem(info, 3);
808 if (text != NULL) {
809 status =
810 PyObject_SetAttrString(self, "filename", filename)
811 || PyObject_SetAttrString(self, "lineno", lineno)
812 || PyObject_SetAttrString(self, "offset", offset)
813 || PyObject_SetAttrString(self, "text", text);
814 Py_DECREF(text);
816 Py_DECREF(offset);
818 Py_DECREF(lineno);
820 Py_DECREF(filename);
822 Py_DECREF(info);
824 if (status)
825 goto finally;
827 Py_INCREF(Py_None);
828 rtnval = Py_None;
830 finally:
831 Py_DECREF(args);
832 return rtnval;
836 /* This is called "my_basename" instead of just "basename" to avoid name
837 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
838 defined, and Python does define that. */
839 static char *
840 my_basename(char *name)
842 char *cp = name;
843 char *result = name;
845 if (name == NULL)
846 return "???";
847 while (*cp != '\0') {
848 if (*cp == SEP)
849 result = cp + 1;
850 ++cp;
852 return result;
856 static PyObject *
857 SyntaxError__str__(PyObject *self, PyObject *args)
859 PyObject *msg;
860 PyObject *str;
861 PyObject *filename, *lineno, *result;
863 if (!PyArg_ParseTuple(args, "O:__str__", &self))
864 return NULL;
866 if (!(msg = PyObject_GetAttrString(self, "msg")))
867 return NULL;
869 str = PyObject_Str(msg);
870 Py_DECREF(msg);
871 result = str;
873 /* XXX -- do all the additional formatting with filename and
874 lineno here */
876 if (str != NULL && PyString_Check(str)) {
877 int have_filename = 0;
878 int have_lineno = 0;
879 char *buffer = NULL;
881 if ((filename = PyObject_GetAttrString(self, "filename")) != NULL)
882 have_filename = PyString_Check(filename);
883 else
884 PyErr_Clear();
886 if ((lineno = PyObject_GetAttrString(self, "lineno")) != NULL)
887 have_lineno = PyInt_Check(lineno);
888 else
889 PyErr_Clear();
891 if (have_filename || have_lineno) {
892 Py_ssize_t bufsize = PyString_GET_SIZE(str) + 64;
893 if (have_filename)
894 bufsize += PyString_GET_SIZE(filename);
896 buffer = PyMem_MALLOC(bufsize);
897 if (buffer != NULL) {
898 if (have_filename && have_lineno)
899 PyOS_snprintf(buffer, bufsize, "%s (%s, line %ld)",
900 PyString_AS_STRING(str),
901 my_basename(PyString_AS_STRING(filename)),
902 PyInt_AsLong(lineno));
903 else if (have_filename)
904 PyOS_snprintf(buffer, bufsize, "%s (%s)",
905 PyString_AS_STRING(str),
906 my_basename(PyString_AS_STRING(filename)));
907 else if (have_lineno)
908 PyOS_snprintf(buffer, bufsize, "%s (line %ld)",
909 PyString_AS_STRING(str),
910 PyInt_AsLong(lineno));
912 result = PyString_FromString(buffer);
913 PyMem_FREE(buffer);
915 if (result == NULL)
916 result = str;
917 else
918 Py_DECREF(str);
921 Py_XDECREF(filename);
922 Py_XDECREF(lineno);
924 return result;
928 static PyMethodDef SyntaxError_methods[] = {
929 {"__init__", SyntaxError__init__, METH_VARARGS},
930 {"__str__", SyntaxError__str__, METH_VARARGS},
931 {NULL, NULL}
935 static PyObject *
936 KeyError__str__(PyObject *self, PyObject *args)
938 PyObject *argsattr;
939 PyObject *result;
941 if (!PyArg_ParseTuple(args, "O:__str__", &self))
942 return NULL;
944 argsattr = PyObject_GetAttrString(self, "args");
945 if (!argsattr)
946 return NULL;
948 /* If args is a tuple of exactly one item, apply repr to args[0].
949 This is done so that e.g. the exception raised by {}[''] prints
950 KeyError: ''
951 rather than the confusing
952 KeyError
953 alone. The downside is that if KeyError is raised with an explanatory
954 string, that string will be displayed in quotes. Too bad.
955 If args is anything else, use the default BaseException__str__().
957 if (PyTuple_Check(argsattr) && PyTuple_GET_SIZE(argsattr) == 1) {
958 PyObject *key = PyTuple_GET_ITEM(argsattr, 0);
959 result = PyObject_Repr(key);
961 else
962 result = BaseException__str__(self, args);
964 Py_DECREF(argsattr);
965 return result;
968 static PyMethodDef KeyError_methods[] = {
969 {"__str__", KeyError__str__, METH_VARARGS},
970 {NULL, NULL}
974 #ifdef Py_USING_UNICODE
975 static
976 int get_int(PyObject *exc, const char *name, Py_ssize_t *value)
978 PyObject *attr = PyObject_GetAttrString(exc, (char *)name);
980 if (!attr)
981 return -1;
982 if (PyInt_Check(attr)) {
983 *value = PyInt_AS_LONG(attr);
984 } else if (PyLong_Check(attr)) {
985 *value = (size_t)PyLong_AsLongLong(attr);
986 if (*value == -1) {
987 Py_DECREF(attr);
988 return -1;
990 } else {
991 PyErr_Format(PyExc_TypeError, "%.200s attribute must be int", name);
992 Py_DECREF(attr);
993 return -1;
995 Py_DECREF(attr);
996 return 0;
1000 static
1001 int set_ssize_t(PyObject *exc, const char *name, Py_ssize_t value)
1003 PyObject *obj = PyInt_FromSsize_t(value);
1004 int result;
1006 if (!obj)
1007 return -1;
1008 result = PyObject_SetAttrString(exc, (char *)name, obj);
1009 Py_DECREF(obj);
1010 return result;
1013 static
1014 PyObject *get_string(PyObject *exc, const char *name)
1016 PyObject *attr = PyObject_GetAttrString(exc, (char *)name);
1018 if (!attr)
1019 return NULL;
1020 if (!PyString_Check(attr)) {
1021 PyErr_Format(PyExc_TypeError, "%.200s attribute must be str", name);
1022 Py_DECREF(attr);
1023 return NULL;
1025 return attr;
1029 static
1030 int set_string(PyObject *exc, const char *name, const char *value)
1032 PyObject *obj = PyString_FromString(value);
1033 int result;
1035 if (!obj)
1036 return -1;
1037 result = PyObject_SetAttrString(exc, (char *)name, obj);
1038 Py_DECREF(obj);
1039 return result;
1043 static
1044 PyObject *get_unicode(PyObject *exc, const char *name)
1046 PyObject *attr = PyObject_GetAttrString(exc, (char *)name);
1048 if (!attr)
1049 return NULL;
1050 if (!PyUnicode_Check(attr)) {
1051 PyErr_Format(PyExc_TypeError, "%.200s attribute must be unicode", name);
1052 Py_DECREF(attr);
1053 return NULL;
1055 return attr;
1058 PyObject * PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1060 return get_string(exc, "encoding");
1063 PyObject * PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1065 return get_string(exc, "encoding");
1068 PyObject *PyUnicodeEncodeError_GetObject(PyObject *exc)
1070 return get_unicode(exc, "object");
1073 PyObject *PyUnicodeDecodeError_GetObject(PyObject *exc)
1075 return get_string(exc, "object");
1078 PyObject *PyUnicodeTranslateError_GetObject(PyObject *exc)
1080 return get_unicode(exc, "object");
1083 int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1085 if (!get_int(exc, "start", start)) {
1086 PyObject *object = PyUnicodeEncodeError_GetObject(exc);
1087 Py_ssize_t size;
1088 if (!object)
1089 return -1;
1090 size = PyUnicode_GET_SIZE(object);
1091 if (*start<0)
1092 *start = 0; /*XXX check for values <0*/
1093 if (*start>=size)
1094 *start = size-1;
1095 Py_DECREF(object);
1096 return 0;
1098 return -1;
1102 int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1104 if (!get_int(exc, "start", start)) {
1105 PyObject *object = PyUnicodeDecodeError_GetObject(exc);
1106 Py_ssize_t size;
1107 if (!object)
1108 return -1;
1109 size = PyString_GET_SIZE(object);
1110 if (*start<0)
1111 *start = 0;
1112 if (*start>=size)
1113 *start = size-1;
1114 Py_DECREF(object);
1115 return 0;
1117 return -1;
1121 int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1123 return PyUnicodeEncodeError_GetStart(exc, start);
1127 int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1129 return set_ssize_t(exc, "start", start);
1133 int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1135 return set_ssize_t(exc, "start", start);
1139 int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1141 return set_ssize_t(exc, "start", start);
1145 int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1147 if (!get_int(exc, "end", end)) {
1148 PyObject *object = PyUnicodeEncodeError_GetObject(exc);
1149 Py_ssize_t size;
1150 if (!object)
1151 return -1;
1152 size = PyUnicode_GET_SIZE(object);
1153 if (*end<1)
1154 *end = 1;
1155 if (*end>size)
1156 *end = size;
1157 Py_DECREF(object);
1158 return 0;
1160 return -1;
1164 int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1166 if (!get_int(exc, "end", end)) {
1167 PyObject *object = PyUnicodeDecodeError_GetObject(exc);
1168 Py_ssize_t size;
1169 if (!object)
1170 return -1;
1171 size = PyString_GET_SIZE(object);
1172 if (*end<1)
1173 *end = 1;
1174 if (*end>size)
1175 *end = size;
1176 Py_DECREF(object);
1177 return 0;
1179 return -1;
1183 int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1185 return PyUnicodeEncodeError_GetEnd(exc, start);
1189 int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1191 return set_ssize_t(exc, "end", end);
1195 int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1197 return set_ssize_t(exc, "end", end);
1201 int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1203 return set_ssize_t(exc, "end", end);
1207 PyObject *PyUnicodeEncodeError_GetReason(PyObject *exc)
1209 return get_string(exc, "reason");
1213 PyObject *PyUnicodeDecodeError_GetReason(PyObject *exc)
1215 return get_string(exc, "reason");
1219 PyObject *PyUnicodeTranslateError_GetReason(PyObject *exc)
1221 return get_string(exc, "reason");
1225 int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1227 return set_string(exc, "reason", reason);
1231 int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1233 return set_string(exc, "reason", reason);
1237 int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1239 return set_string(exc, "reason", reason);
1243 static PyObject *
1244 UnicodeError__init__(PyObject *self, PyObject *args, PyTypeObject *objecttype)
1246 PyObject *rtnval = NULL;
1247 PyObject *encoding;
1248 PyObject *object;
1249 PyObject *start;
1250 PyObject *end;
1251 PyObject *reason;
1253 if (!(self = get_self(args)))
1254 return NULL;
1256 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
1257 return NULL;
1259 if (!set_args_and_message(self, args)) {
1260 Py_DECREF(args);
1261 return NULL;
1264 if (!PyArg_ParseTuple(args, "O!O!O!O!O!",
1265 &PyString_Type, &encoding,
1266 objecttype, &object,
1267 &PyInt_Type, &start,
1268 &PyInt_Type, &end,
1269 &PyString_Type, &reason))
1270 goto finally;
1272 if (PyObject_SetAttrString(self, "encoding", encoding))
1273 goto finally;
1274 if (PyObject_SetAttrString(self, "object", object))
1275 goto finally;
1276 if (PyObject_SetAttrString(self, "start", start))
1277 goto finally;
1278 if (PyObject_SetAttrString(self, "end", end))
1279 goto finally;
1280 if (PyObject_SetAttrString(self, "reason", reason))
1281 goto finally;
1283 Py_INCREF(Py_None);
1284 rtnval = Py_None;
1286 finally:
1287 Py_DECREF(args);
1288 return rtnval;
1292 static PyObject *
1293 UnicodeEncodeError__init__(PyObject *self, PyObject *args)
1295 return UnicodeError__init__(self, args, &PyUnicode_Type);
1298 static PyObject *
1299 UnicodeEncodeError__str__(PyObject *self, PyObject *arg)
1301 PyObject *encodingObj = NULL;
1302 PyObject *objectObj = NULL;
1303 Py_ssize_t start;
1304 Py_ssize_t end;
1305 PyObject *reasonObj = NULL;
1306 PyObject *result = NULL;
1308 self = arg;
1310 if (!(encodingObj = PyUnicodeEncodeError_GetEncoding(self)))
1311 goto error;
1313 if (!(objectObj = PyUnicodeEncodeError_GetObject(self)))
1314 goto error;
1316 if (PyUnicodeEncodeError_GetStart(self, &start))
1317 goto error;
1319 if (PyUnicodeEncodeError_GetEnd(self, &end))
1320 goto error;
1322 if (!(reasonObj = PyUnicodeEncodeError_GetReason(self)))
1323 goto error;
1325 if (end==start+1) {
1326 int badchar = (int)PyUnicode_AS_UNICODE(objectObj)[start];
1327 char badchar_str[20];
1328 if (badchar <= 0xff)
1329 PyOS_snprintf(badchar_str, sizeof(badchar_str), "x%02x", badchar);
1330 else if (badchar <= 0xffff)
1331 PyOS_snprintf(badchar_str, sizeof(badchar_str), "u%04x", badchar);
1332 else
1333 PyOS_snprintf(badchar_str, sizeof(badchar_str), "U%08x", badchar);
1334 result = PyString_FromFormat(
1335 "'%.400s' codec can't encode character u'\\%s' in position %zd: %.400s",
1336 PyString_AS_STRING(encodingObj),
1337 badchar_str,
1338 start,
1339 PyString_AS_STRING(reasonObj)
1342 else {
1343 result = PyString_FromFormat(
1344 "'%.400s' codec can't encode characters in position %zd-%zd: %.400s",
1345 PyString_AS_STRING(encodingObj),
1346 start,
1347 (end-1),
1348 PyString_AS_STRING(reasonObj)
1352 error:
1353 Py_XDECREF(reasonObj);
1354 Py_XDECREF(objectObj);
1355 Py_XDECREF(encodingObj);
1356 return result;
1359 static PyMethodDef UnicodeEncodeError_methods[] = {
1360 {"__init__", UnicodeEncodeError__init__, METH_VARARGS},
1361 {"__str__", UnicodeEncodeError__str__, METH_O},
1362 {NULL, NULL}
1366 PyObject * PyUnicodeEncodeError_Create(
1367 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1368 Py_ssize_t start, Py_ssize_t end, const char *reason)
1370 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
1371 encoding, object, length, start, end, reason);
1375 static PyObject *
1376 UnicodeDecodeError__init__(PyObject *self, PyObject *args)
1378 return UnicodeError__init__(self, args, &PyString_Type);
1381 static PyObject *
1382 UnicodeDecodeError__str__(PyObject *self, PyObject *arg)
1384 PyObject *encodingObj = NULL;
1385 PyObject *objectObj = NULL;
1386 Py_ssize_t start;
1387 Py_ssize_t end;
1388 PyObject *reasonObj = NULL;
1389 PyObject *result = NULL;
1391 self = arg;
1393 if (!(encodingObj = PyUnicodeDecodeError_GetEncoding(self)))
1394 goto error;
1396 if (!(objectObj = PyUnicodeDecodeError_GetObject(self)))
1397 goto error;
1399 if (PyUnicodeDecodeError_GetStart(self, &start))
1400 goto error;
1402 if (PyUnicodeDecodeError_GetEnd(self, &end))
1403 goto error;
1405 if (!(reasonObj = PyUnicodeDecodeError_GetReason(self)))
1406 goto error;
1408 if (end==start+1) {
1409 /* FromFormat does not support %02x, so format that separately */
1410 char byte[4];
1411 PyOS_snprintf(byte, sizeof(byte), "%02x",
1412 ((int)PyString_AS_STRING(objectObj)[start])&0xff);
1413 result = PyString_FromFormat(
1414 "'%.400s' codec can't decode byte 0x%s in position %zd: %.400s",
1415 PyString_AS_STRING(encodingObj),
1416 byte,
1417 start,
1418 PyString_AS_STRING(reasonObj)
1421 else {
1422 result = PyString_FromFormat(
1423 "'%.400s' codec can't decode bytes in position %zd-%zd: %.400s",
1424 PyString_AS_STRING(encodingObj),
1425 start,
1426 (end-1),
1427 PyString_AS_STRING(reasonObj)
1432 error:
1433 Py_XDECREF(reasonObj);
1434 Py_XDECREF(objectObj);
1435 Py_XDECREF(encodingObj);
1436 return result;
1439 static PyMethodDef UnicodeDecodeError_methods[] = {
1440 {"__init__", UnicodeDecodeError__init__, METH_VARARGS},
1441 {"__str__", UnicodeDecodeError__str__, METH_O},
1442 {NULL, NULL}
1446 PyObject * PyUnicodeDecodeError_Create(
1447 const char *encoding, const char *object, Py_ssize_t length,
1448 Py_ssize_t start, Py_ssize_t end, const char *reason)
1450 assert(length < INT_MAX);
1451 assert(start < INT_MAX);
1452 assert(end < INT_MAX);
1453 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "ss#iis",
1454 encoding, object, (int)length, (int)start, (int)end, reason);
1458 static PyObject *
1459 UnicodeTranslateError__init__(PyObject *self, PyObject *args)
1461 PyObject *rtnval = NULL;
1462 PyObject *object;
1463 PyObject *start;
1464 PyObject *end;
1465 PyObject *reason;
1467 if (!(self = get_self(args)))
1468 return NULL;
1470 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
1471 return NULL;
1473 if (!set_args_and_message(self, args)) {
1474 Py_DECREF(args);
1475 return NULL;
1478 if (!PyArg_ParseTuple(args, "O!O!O!O!",
1479 &PyUnicode_Type, &object,
1480 &PyInt_Type, &start,
1481 &PyInt_Type, &end,
1482 &PyString_Type, &reason))
1483 goto finally;
1485 if (PyObject_SetAttrString(self, "object", object))
1486 goto finally;
1487 if (PyObject_SetAttrString(self, "start", start))
1488 goto finally;
1489 if (PyObject_SetAttrString(self, "end", end))
1490 goto finally;
1491 if (PyObject_SetAttrString(self, "reason", reason))
1492 goto finally;
1494 rtnval = Py_None;
1495 Py_INCREF(rtnval);
1497 finally:
1498 Py_DECREF(args);
1499 return rtnval;
1503 static PyObject *
1504 UnicodeTranslateError__str__(PyObject *self, PyObject *arg)
1506 PyObject *objectObj = NULL;
1507 Py_ssize_t start;
1508 Py_ssize_t end;
1509 PyObject *reasonObj = NULL;
1510 PyObject *result = NULL;
1512 self = arg;
1514 if (!(objectObj = PyUnicodeTranslateError_GetObject(self)))
1515 goto error;
1517 if (PyUnicodeTranslateError_GetStart(self, &start))
1518 goto error;
1520 if (PyUnicodeTranslateError_GetEnd(self, &end))
1521 goto error;
1523 if (!(reasonObj = PyUnicodeTranslateError_GetReason(self)))
1524 goto error;
1526 if (end==start+1) {
1527 int badchar = (int)PyUnicode_AS_UNICODE(objectObj)[start];
1528 char badchar_str[20];
1529 if (badchar <= 0xff)
1530 PyOS_snprintf(badchar_str, sizeof(badchar_str), "x%02x", badchar);
1531 else if (badchar <= 0xffff)
1532 PyOS_snprintf(badchar_str, sizeof(badchar_str), "u%04x", badchar);
1533 else
1534 PyOS_snprintf(badchar_str, sizeof(badchar_str), "U%08x", badchar);
1535 result = PyString_FromFormat(
1536 "can't translate character u'\\%s' in position %zd: %.400s",
1537 badchar_str,
1538 start,
1539 PyString_AS_STRING(reasonObj)
1542 else {
1543 result = PyString_FromFormat(
1544 "can't translate characters in position %zd-%zd: %.400s",
1545 start,
1546 (end-1),
1547 PyString_AS_STRING(reasonObj)
1551 error:
1552 Py_XDECREF(reasonObj);
1553 Py_XDECREF(objectObj);
1554 return result;
1557 static PyMethodDef UnicodeTranslateError_methods[] = {
1558 {"__init__", UnicodeTranslateError__init__, METH_VARARGS},
1559 {"__str__", UnicodeTranslateError__str__, METH_O},
1560 {NULL, NULL}
1564 PyObject * PyUnicodeTranslateError_Create(
1565 const Py_UNICODE *object, Py_ssize_t length,
1566 Py_ssize_t start, Py_ssize_t end, const char *reason)
1568 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#iis",
1569 object, length, start, end, reason);
1571 #endif
1575 /* Exception doc strings */
1577 PyDoc_STRVAR(AssertionError__doc__, "Assertion failed.");
1579 PyDoc_STRVAR(LookupError__doc__, "Base class for lookup errors.");
1581 PyDoc_STRVAR(IndexError__doc__, "Sequence index out of range.");
1583 PyDoc_STRVAR(KeyError__doc__, "Mapping key not found.");
1585 PyDoc_STRVAR(ArithmeticError__doc__, "Base class for arithmetic errors.");
1587 PyDoc_STRVAR(OverflowError__doc__, "Result too large to be represented.");
1589 PyDoc_STRVAR(ZeroDivisionError__doc__,
1590 "Second argument to a division or modulo operation was zero.");
1592 PyDoc_STRVAR(FloatingPointError__doc__, "Floating point operation failed.");
1594 PyDoc_STRVAR(ValueError__doc__,
1595 "Inappropriate argument value (of correct type).");
1597 PyDoc_STRVAR(UnicodeError__doc__, "Unicode related error.");
1599 #ifdef Py_USING_UNICODE
1600 PyDoc_STRVAR(UnicodeEncodeError__doc__, "Unicode encoding error.");
1602 PyDoc_STRVAR(UnicodeDecodeError__doc__, "Unicode decoding error.");
1604 PyDoc_STRVAR(UnicodeTranslateError__doc__, "Unicode translation error.");
1605 #endif
1607 PyDoc_STRVAR(SystemError__doc__,
1608 "Internal error in the Python interpreter.\n\
1610 Please report this to the Python maintainer, along with the traceback,\n\
1611 the Python version, and the hardware/OS platform and version.");
1613 PyDoc_STRVAR(ReferenceError__doc__,
1614 "Weak ref proxy used after referent went away.");
1616 PyDoc_STRVAR(MemoryError__doc__, "Out of memory.");
1618 PyDoc_STRVAR(IndentationError__doc__, "Improper indentation.");
1620 PyDoc_STRVAR(TabError__doc__, "Improper mixture of spaces and tabs.");
1622 /* Warning category docstrings */
1624 PyDoc_STRVAR(Warning__doc__, "Base class for warning categories.");
1626 PyDoc_STRVAR(UserWarning__doc__,
1627 "Base class for warnings generated by user code.");
1629 PyDoc_STRVAR(DeprecationWarning__doc__,
1630 "Base class for warnings about deprecated features.");
1632 PyDoc_STRVAR(PendingDeprecationWarning__doc__,
1633 "Base class for warnings about features which will be deprecated "
1634 "in the future.");
1636 PyDoc_STRVAR(SyntaxWarning__doc__,
1637 "Base class for warnings about dubious syntax.");
1639 PyDoc_STRVAR(OverflowWarning__doc__,
1640 "Base class for warnings about numeric overflow. Won't exist in Python 2.5.");
1642 PyDoc_STRVAR(RuntimeWarning__doc__,
1643 "Base class for warnings about dubious runtime behavior.");
1645 PyDoc_STRVAR(FutureWarning__doc__,
1646 "Base class for warnings about constructs that will change semantically "
1647 "in the future.");
1651 /* module global functions */
1652 static PyMethodDef functions[] = {
1653 /* Sentinel */
1654 {NULL, NULL}
1659 /* Global C API defined exceptions */
1661 PyObject *PyExc_BaseException;
1662 PyObject *PyExc_Exception;
1663 PyObject *PyExc_StopIteration;
1664 PyObject *PyExc_GeneratorExit;
1665 PyObject *PyExc_StandardError;
1666 PyObject *PyExc_ArithmeticError;
1667 PyObject *PyExc_LookupError;
1669 PyObject *PyExc_AssertionError;
1670 PyObject *PyExc_AttributeError;
1671 PyObject *PyExc_EOFError;
1672 PyObject *PyExc_FloatingPointError;
1673 PyObject *PyExc_EnvironmentError;
1674 PyObject *PyExc_IOError;
1675 PyObject *PyExc_OSError;
1676 PyObject *PyExc_ImportError;
1677 PyObject *PyExc_IndexError;
1678 PyObject *PyExc_KeyError;
1679 PyObject *PyExc_KeyboardInterrupt;
1680 PyObject *PyExc_MemoryError;
1681 PyObject *PyExc_NameError;
1682 PyObject *PyExc_OverflowError;
1683 PyObject *PyExc_RuntimeError;
1684 PyObject *PyExc_NotImplementedError;
1685 PyObject *PyExc_SyntaxError;
1686 PyObject *PyExc_IndentationError;
1687 PyObject *PyExc_TabError;
1688 PyObject *PyExc_ReferenceError;
1689 PyObject *PyExc_SystemError;
1690 PyObject *PyExc_SystemExit;
1691 PyObject *PyExc_UnboundLocalError;
1692 PyObject *PyExc_UnicodeError;
1693 PyObject *PyExc_UnicodeEncodeError;
1694 PyObject *PyExc_UnicodeDecodeError;
1695 PyObject *PyExc_UnicodeTranslateError;
1696 PyObject *PyExc_TypeError;
1697 PyObject *PyExc_ValueError;
1698 PyObject *PyExc_ZeroDivisionError;
1699 #ifdef MS_WINDOWS
1700 PyObject *PyExc_WindowsError;
1701 #endif
1702 #ifdef __VMS
1703 PyObject *PyExc_VMSError;
1704 #endif
1706 /* Pre-computed MemoryError instance. Best to create this as early as
1707 * possible and not wait until a MemoryError is actually raised!
1709 PyObject *PyExc_MemoryErrorInst;
1711 /* Predefined warning categories */
1712 PyObject *PyExc_Warning;
1713 PyObject *PyExc_UserWarning;
1714 PyObject *PyExc_DeprecationWarning;
1715 PyObject *PyExc_PendingDeprecationWarning;
1716 PyObject *PyExc_SyntaxWarning;
1717 /* PyExc_OverflowWarning should be removed for Python 2.5 */
1718 PyObject *PyExc_OverflowWarning;
1719 PyObject *PyExc_RuntimeWarning;
1720 PyObject *PyExc_FutureWarning;
1724 /* mapping between exception names and their PyObject ** */
1725 static struct {
1726 char *name;
1727 PyObject **exc;
1728 PyObject **base; /* NULL == PyExc_StandardError */
1729 char *docstr;
1730 PyMethodDef *methods;
1731 int (*classinit)(PyObject *);
1732 } exctable[] = {
1734 * The first four classes MUST appear in exactly this order
1736 {"BaseException", &PyExc_BaseException},
1737 {"Exception", &PyExc_Exception, &PyExc_BaseException, Exception__doc__},
1738 {"StopIteration", &PyExc_StopIteration, &PyExc_Exception,
1739 StopIteration__doc__},
1740 {"GeneratorExit", &PyExc_GeneratorExit, &PyExc_Exception,
1741 GeneratorExit__doc__},
1742 {"StandardError", &PyExc_StandardError, &PyExc_Exception,
1743 StandardError__doc__},
1744 {"TypeError", &PyExc_TypeError, 0, TypeError__doc__},
1746 * The rest appear in depth-first order of the hierarchy
1748 {"SystemExit", &PyExc_SystemExit, &PyExc_BaseException, SystemExit__doc__,
1749 SystemExit_methods},
1750 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, &PyExc_BaseException,
1751 KeyboardInterrupt__doc__},
1752 {"ImportError", &PyExc_ImportError, 0, ImportError__doc__},
1753 {"EnvironmentError", &PyExc_EnvironmentError, 0, EnvironmentError__doc__,
1754 EnvironmentError_methods},
1755 {"IOError", &PyExc_IOError, &PyExc_EnvironmentError, IOError__doc__},
1756 {"OSError", &PyExc_OSError, &PyExc_EnvironmentError, OSError__doc__},
1757 #ifdef MS_WINDOWS
1758 {"WindowsError", &PyExc_WindowsError, &PyExc_OSError,
1759 WindowsError__doc__},
1760 #endif /* MS_WINDOWS */
1761 #ifdef __VMS
1762 {"VMSError", &PyExc_VMSError, &PyExc_OSError,
1763 VMSError__doc__},
1764 #endif
1765 {"EOFError", &PyExc_EOFError, 0, EOFError__doc__},
1766 {"RuntimeError", &PyExc_RuntimeError, 0, RuntimeError__doc__},
1767 {"NotImplementedError", &PyExc_NotImplementedError,
1768 &PyExc_RuntimeError, NotImplementedError__doc__},
1769 {"NameError", &PyExc_NameError, 0, NameError__doc__},
1770 {"UnboundLocalError", &PyExc_UnboundLocalError, &PyExc_NameError,
1771 UnboundLocalError__doc__},
1772 {"AttributeError", &PyExc_AttributeError, 0, AttributeError__doc__},
1773 {"SyntaxError", &PyExc_SyntaxError, 0, SyntaxError__doc__,
1774 SyntaxError_methods, SyntaxError__classinit__},
1775 {"IndentationError", &PyExc_IndentationError, &PyExc_SyntaxError,
1776 IndentationError__doc__},
1777 {"TabError", &PyExc_TabError, &PyExc_IndentationError,
1778 TabError__doc__},
1779 {"AssertionError", &PyExc_AssertionError, 0, AssertionError__doc__},
1780 {"LookupError", &PyExc_LookupError, 0, LookupError__doc__},
1781 {"IndexError", &PyExc_IndexError, &PyExc_LookupError,
1782 IndexError__doc__},
1783 {"KeyError", &PyExc_KeyError, &PyExc_LookupError,
1784 KeyError__doc__, KeyError_methods},
1785 {"ArithmeticError", &PyExc_ArithmeticError, 0, ArithmeticError__doc__},
1786 {"OverflowError", &PyExc_OverflowError, &PyExc_ArithmeticError,
1787 OverflowError__doc__},
1788 {"ZeroDivisionError", &PyExc_ZeroDivisionError, &PyExc_ArithmeticError,
1789 ZeroDivisionError__doc__},
1790 {"FloatingPointError", &PyExc_FloatingPointError, &PyExc_ArithmeticError,
1791 FloatingPointError__doc__},
1792 {"ValueError", &PyExc_ValueError, 0, ValueError__doc__},
1793 {"UnicodeError", &PyExc_UnicodeError, &PyExc_ValueError, UnicodeError__doc__},
1794 #ifdef Py_USING_UNICODE
1795 {"UnicodeEncodeError", &PyExc_UnicodeEncodeError, &PyExc_UnicodeError,
1796 UnicodeEncodeError__doc__, UnicodeEncodeError_methods},
1797 {"UnicodeDecodeError", &PyExc_UnicodeDecodeError, &PyExc_UnicodeError,
1798 UnicodeDecodeError__doc__, UnicodeDecodeError_methods},
1799 {"UnicodeTranslateError", &PyExc_UnicodeTranslateError, &PyExc_UnicodeError,
1800 UnicodeTranslateError__doc__, UnicodeTranslateError_methods},
1801 #endif
1802 {"ReferenceError", &PyExc_ReferenceError, 0, ReferenceError__doc__},
1803 {"SystemError", &PyExc_SystemError, 0, SystemError__doc__},
1804 {"MemoryError", &PyExc_MemoryError, 0, MemoryError__doc__},
1805 /* Warning categories */
1806 {"Warning", &PyExc_Warning, &PyExc_Exception, Warning__doc__},
1807 {"UserWarning", &PyExc_UserWarning, &PyExc_Warning, UserWarning__doc__},
1808 {"DeprecationWarning", &PyExc_DeprecationWarning, &PyExc_Warning,
1809 DeprecationWarning__doc__},
1810 {"PendingDeprecationWarning", &PyExc_PendingDeprecationWarning, &PyExc_Warning,
1811 PendingDeprecationWarning__doc__},
1812 {"SyntaxWarning", &PyExc_SyntaxWarning, &PyExc_Warning, SyntaxWarning__doc__},
1813 /* OverflowWarning should be removed for Python 2.5 */
1814 {"OverflowWarning", &PyExc_OverflowWarning, &PyExc_Warning,
1815 OverflowWarning__doc__},
1816 {"RuntimeWarning", &PyExc_RuntimeWarning, &PyExc_Warning,
1817 RuntimeWarning__doc__},
1818 {"FutureWarning", &PyExc_FutureWarning, &PyExc_Warning,
1819 FutureWarning__doc__},
1820 /* Sentinel */
1821 {NULL}
1826 void
1827 _PyExc_Init(void)
1829 char *modulename = "exceptions";
1830 Py_ssize_t modnamesz = strlen(modulename);
1831 int i;
1832 PyObject *me, *mydict, *bltinmod, *bdict, *doc, *args;
1834 me = Py_InitModule(modulename, functions);
1835 if (me == NULL)
1836 goto err;
1837 mydict = PyModule_GetDict(me);
1838 if (mydict == NULL)
1839 goto err;
1840 bltinmod = PyImport_ImportModule("__builtin__");
1841 if (bltinmod == NULL)
1842 goto err;
1843 bdict = PyModule_GetDict(bltinmod);
1844 if (bdict == NULL)
1845 goto err;
1846 doc = PyString_FromString(module__doc__);
1847 if (doc == NULL)
1848 goto err;
1850 i = PyDict_SetItemString(mydict, "__doc__", doc);
1851 Py_DECREF(doc);
1852 if (i < 0) {
1853 err:
1854 Py_FatalError("exceptions bootstrapping error.");
1855 return;
1858 /* This is the base class of all exceptions, so make it first. */
1859 if (make_BaseException(modulename) ||
1860 PyDict_SetItemString(mydict, "BaseException", PyExc_BaseException) ||
1861 PyDict_SetItemString(bdict, "BaseException", PyExc_BaseException))
1863 Py_FatalError("Base class `BaseException' could not be created.");
1866 /* Now we can programmatically create all the remaining exceptions.
1867 * Remember to start the loop at 1 to skip Exceptions.
1869 for (i=1; exctable[i].name; i++) {
1870 int status;
1871 char *cname = PyMem_NEW(char, modnamesz+strlen(exctable[i].name)+2);
1872 PyObject *base;
1874 (void)strcpy(cname, modulename);
1875 (void)strcat(cname, ".");
1876 (void)strcat(cname, exctable[i].name);
1878 if (exctable[i].base == 0)
1879 base = PyExc_StandardError;
1880 else
1881 base = *exctable[i].base;
1883 status = make_class(exctable[i].exc, base, cname,
1884 exctable[i].methods,
1885 exctable[i].docstr);
1887 PyMem_DEL(cname);
1889 if (status)
1890 Py_FatalError("Standard exception classes could not be created.");
1892 if (exctable[i].classinit) {
1893 status = (*exctable[i].classinit)(*exctable[i].exc);
1894 if (status)
1895 Py_FatalError("An exception class could not be initialized.");
1898 /* Now insert the class into both this module and the __builtin__
1899 * module.
1901 if (PyDict_SetItemString(mydict, exctable[i].name, *exctable[i].exc) ||
1902 PyDict_SetItemString(bdict, exctable[i].name, *exctable[i].exc))
1904 Py_FatalError("Module dictionary insertion problem.");
1908 /* Now we need to pre-allocate a MemoryError instance */
1909 args = PyTuple_New(0);
1910 if (!args ||
1911 !(PyExc_MemoryErrorInst = PyEval_CallObject(PyExc_MemoryError, args)))
1913 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
1915 Py_DECREF(args);
1917 /* We're done with __builtin__ */
1918 Py_DECREF(bltinmod);
1922 void
1923 _PyExc_Fini(void)
1925 int i;
1927 Py_XDECREF(PyExc_MemoryErrorInst);
1928 PyExc_MemoryErrorInst = NULL;
1930 for (i=0; exctable[i].name; i++) {
1931 /* clear the class's dictionary, freeing up circular references
1932 * between the class and its methods.
1934 PyObject* cdict = PyObject_GetAttrString(*exctable[i].exc, "__dict__");
1935 PyDict_Clear(cdict);
1936 Py_DECREF(cdict);
1938 /* Now decref the exception class */
1939 Py_XDECREF(*exctable[i].exc);
1940 *exctable[i].exc = NULL;