Files for 2.1b1 distribution.
[python/dscho.git] / Python / exceptions.c
blobf262ef2a97d3f6d59ba8e8fd6aae4507f831736d
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.
10 * history:
11 * 98-08-19 fl created (for pyexe)
12 * 00-02-08 fl updated for 1.5.2
13 * 26-May-2000 baw vetted for Python 1.6
15 * written by Fredrik Lundh
16 * modifications, additions, cleanups, and proofreading by Barry Warsaw
18 * Copyright (c) 1998-2000 by Secret Labs AB. All rights reserved.
21 #include "Python.h"
22 #include "osdefs.h"
24 /* Caution: MS Visual C++ 6 errors if a single string literal exceeds
25 * 2Kb. So the module docstring has been broken roughly in half, using
26 * compile-time literal concatenation.
28 static char
29 module__doc__[] =
30 "Python's standard exception class hierarchy.\n\
31 \n\
32 Before Python 1.5, the standard exceptions were all simple string objects.\n\
33 In Python 1.5, the standard exceptions were converted to classes organized\n\
34 into a relatively flat hierarchy. String-based standard exceptions were\n\
35 optional, or used as a fallback if some problem occurred while importing\n\
36 the exception module. With Python 1.6, optional string-based standard\n\
37 exceptions were removed (along with the -X command line flag).\n\
38 \n\
39 The class exceptions were implemented in such a way as to be almost\n\
40 completely backward compatible. Some tricky uses of IOError could\n\
41 potentially have broken, but by Python 1.6, all of these should have\n\
42 been fixed. As of Python 1.6, the class-based standard exceptions are\n\
43 now implemented in C, and are guaranteed to exist in the Python\n\
44 interpreter.\n\
45 \n\
46 Here is a rundown of the class hierarchy. The classes found here are\n\
47 inserted into both the exceptions module and the `built-in' module. It is\n\
48 recommended that user defined class based exceptions be derived from the\n\
49 `Exception' class, although this is currently not enforced.\n"
50 /* keep string pieces "small" */
51 "\n\
52 Exception\n\
53 |\n\
54 +-- SystemExit\n\
55 +-- StandardError\n\
56 | |\n\
57 | +-- KeyboardInterrupt\n\
58 | +-- ImportError\n\
59 | +-- EnvironmentError\n\
60 | | |\n\
61 | | +-- IOError\n\
62 | | +-- OSError\n\
63 | | |\n\
64 | | +-- WindowsError\n\
65 | |\n\
66 | +-- EOFError\n\
67 | +-- RuntimeError\n\
68 | | |\n\
69 | | +-- NotImplementedError\n\
70 | |\n\
71 | +-- NameError\n\
72 | | |\n\
73 | | +-- UnboundLocalError\n\
74 | |\n\
75 | +-- AttributeError\n\
76 | +-- SyntaxError\n\
77 | | |\n\
78 | | +-- IndentationError\n\
79 | | |\n\
80 | | +-- TabError\n\
81 | |\n\
82 | +-- TypeError\n\
83 | +-- AssertionError\n\
84 | +-- LookupError\n\
85 | | |\n\
86 | | +-- IndexError\n\
87 | | +-- KeyError\n\
88 | |\n\
89 | +-- ArithmeticError\n\
90 | | |\n\
91 | | +-- OverflowError\n\
92 | | +-- ZeroDivisionError\n\
93 | | +-- FloatingPointError\n\
94 | |\n\
95 | +-- ValueError\n\
96 | | |\n\
97 | | +-- UnicodeError\n\
98 | |\n\
99 | +-- SystemError\n\
100 | +-- MemoryError\n\
101 |\n\
102 +---Warning\n\
103 |\n\
104 +-- UserWarning\n\
105 +-- DeprecationWarning\n\
106 +-- SyntaxWarning\n\
107 +-- RuntimeWarning";
110 /* Helper function for populating a dictionary with method wrappers. */
111 static int
112 populate_methods(PyObject *klass, PyObject *dict, PyMethodDef *methods)
114 if (!methods)
115 return 0;
117 while (methods->ml_name) {
118 /* get a wrapper for the built-in function */
119 PyObject *func = PyCFunction_New(methods, NULL);
120 PyObject *meth;
121 int status;
123 if (!func)
124 return -1;
126 /* turn the function into an unbound method */
127 if (!(meth = PyMethod_New(func, NULL, klass))) {
128 Py_DECREF(func);
129 return -1;
132 /* add method to dictionary */
133 status = PyDict_SetItemString(dict, methods->ml_name, meth);
134 Py_DECREF(meth);
135 Py_DECREF(func);
137 /* stop now if an error occurred, otherwise do the next method */
138 if (status)
139 return status;
141 methods++;
143 return 0;
148 /* This function is used to create all subsequent exception classes. */
149 static int
150 make_class(PyObject **klass, PyObject *base,
151 char *name, PyMethodDef *methods,
152 char *docstr)
154 PyObject *dict = PyDict_New();
155 PyObject *str = NULL;
156 int status = -1;
158 if (!dict)
159 return -1;
161 /* If an error occurs from here on, goto finally instead of explicitly
162 * returning NULL.
165 if (docstr) {
166 if (!(str = PyString_FromString(docstr)))
167 goto finally;
168 if (PyDict_SetItemString(dict, "__doc__", str))
169 goto finally;
172 if (!(*klass = PyErr_NewException(name, base, dict)))
173 goto finally;
175 if (populate_methods(*klass, dict, methods)) {
176 Py_DECREF(*klass);
177 *klass = NULL;
178 goto finally;
181 status = 0;
183 finally:
184 Py_XDECREF(dict);
185 Py_XDECREF(str);
186 return status;
190 /* Use this for *args signatures, otherwise just use PyArg_ParseTuple() */
191 static PyObject *
192 get_self(PyObject *args)
194 PyObject *self = PyTuple_GetItem(args, 0);
195 if (!self) {
196 /* Watch out for being called to early in the bootstrapping process */
197 if (PyExc_TypeError) {
198 PyErr_SetString(PyExc_TypeError,
199 "unbound method must be called with instance as first argument");
201 return NULL;
203 return self;
208 /* Notes on bootstrapping the exception classes.
210 * First thing we create is the base class for all exceptions, called
211 * appropriately enough: Exception. Creation of this class makes no
212 * assumptions about the existence of any other exception class -- except
213 * for TypeError, which can conditionally exist.
215 * Next, StandardError is created (which is quite simple) followed by
216 * TypeError, because the instantiation of other exceptions can potentially
217 * throw a TypeError. Once these exceptions are created, all the others
218 * can be created in any order. See the static exctable below for the
219 * explicit bootstrap order.
221 * All classes after Exception can be created using PyErr_NewException().
224 static char
225 Exception__doc__[] = "Common base class for all exceptions.";
228 static PyObject *
229 Exception__init__(PyObject *self, PyObject *args)
231 int status;
233 if (!(self = get_self(args)))
234 return NULL;
236 /* set args attribute */
237 /* XXX size is only a hint */
238 args = PySequence_GetSlice(args, 1, PySequence_Size(args));
239 if (!args)
240 return NULL;
241 status = PyObject_SetAttrString(self, "args", args);
242 Py_DECREF(args);
243 if (status < 0)
244 return NULL;
246 Py_INCREF(Py_None);
247 return Py_None;
251 static PyObject *
252 Exception__str__(PyObject *self, PyObject *args)
254 PyObject *out;
256 if (!PyArg_ParseTuple(args, "O:__str__", &self))
257 return NULL;
259 args = PyObject_GetAttrString(self, "args");
260 if (!args)
261 return NULL;
263 switch (PySequence_Size(args)) {
264 case 0:
265 out = PyString_FromString("");
266 break;
267 case 1:
269 PyObject *tmp = PySequence_GetItem(args, 0);
270 if (tmp) {
271 out = PyObject_Str(tmp);
272 Py_DECREF(tmp);
274 else
275 out = NULL;
276 break;
278 default:
279 out = PyObject_Str(args);
280 break;
283 Py_DECREF(args);
284 return out;
288 static PyObject *
289 Exception__getitem__(PyObject *self, PyObject *args)
291 PyObject *out;
292 PyObject *index;
294 if (!PyArg_ParseTuple(args, "OO:__getitem__", &self, &index))
295 return NULL;
297 args = PyObject_GetAttrString(self, "args");
298 if (!args)
299 return NULL;
301 out = PyObject_GetItem(args, index);
302 Py_DECREF(args);
303 return out;
307 static PyMethodDef
308 Exception_methods[] = {
309 /* methods for the Exception class */
310 { "__getitem__", Exception__getitem__, METH_VARARGS},
311 { "__str__", Exception__str__, METH_VARARGS},
312 { "__init__", Exception__init__, METH_VARARGS},
313 { NULL, NULL }
317 static int
318 make_Exception(char *modulename)
320 PyObject *dict = PyDict_New();
321 PyObject *str = NULL;
322 PyObject *name = NULL;
323 int status = -1;
325 if (!dict)
326 return -1;
328 /* If an error occurs from here on, goto finally instead of explicitly
329 * returning NULL.
332 if (!(str = PyString_FromString(modulename)))
333 goto finally;
334 if (PyDict_SetItemString(dict, "__module__", str))
335 goto finally;
336 Py_DECREF(str);
337 if (!(str = PyString_FromString(Exception__doc__)))
338 goto finally;
339 if (PyDict_SetItemString(dict, "__doc__", str))
340 goto finally;
342 if (!(name = PyString_FromString("Exception")))
343 goto finally;
345 if (!(PyExc_Exception = PyClass_New(NULL, dict, name)))
346 goto finally;
348 /* Now populate the dictionary with the method suite */
349 if (populate_methods(PyExc_Exception, dict, Exception_methods))
350 /* Don't need to reclaim PyExc_Exception here because that'll
351 * happen during interpreter shutdown.
353 goto finally;
355 status = 0;
357 finally:
358 Py_XDECREF(dict);
359 Py_XDECREF(str);
360 Py_XDECREF(name);
361 return status;
366 static char
367 StandardError__doc__[] = "Base class for all standard Python exceptions.";
369 static char
370 TypeError__doc__[] = "Inappropriate argument type.";
374 static char
375 SystemExit__doc__[] = "Request to exit from the interpreter.";
378 static PyObject *
379 SystemExit__init__(PyObject *self, PyObject *args)
381 PyObject *code;
382 int status;
384 if (!(self = get_self(args)))
385 return NULL;
387 /* Set args attribute. */
388 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
389 return NULL;
391 status = PyObject_SetAttrString(self, "args", args);
392 if (status < 0) {
393 Py_DECREF(args);
394 return NULL;
397 /* set code attribute */
398 switch (PySequence_Size(args)) {
399 case 0:
400 Py_INCREF(Py_None);
401 code = Py_None;
402 break;
403 case 1:
404 code = PySequence_GetItem(args, 0);
405 break;
406 default:
407 Py_INCREF(args);
408 code = args;
409 break;
412 status = PyObject_SetAttrString(self, "code", code);
413 Py_DECREF(code);
414 Py_DECREF(args);
415 if (status < 0)
416 return NULL;
418 Py_INCREF(Py_None);
419 return Py_None;
423 PyMethodDef SystemExit_methods[] = {
424 { "__init__", SystemExit__init__, METH_VARARGS},
425 {NULL, NULL}
430 static char
431 KeyboardInterrupt__doc__[] = "Program interrupted by user.";
433 static char
434 ImportError__doc__[] =
435 "Import can't find module, or can't find name in module.";
439 static char
440 EnvironmentError__doc__[] = "Base class for I/O related errors.";
443 static PyObject *
444 EnvironmentError__init__(PyObject *self, PyObject *args)
446 PyObject *item0 = NULL;
447 PyObject *item1 = NULL;
448 PyObject *item2 = NULL;
449 PyObject *subslice = NULL;
450 PyObject *rtnval = NULL;
452 if (!(self = get_self(args)))
453 return NULL;
455 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
456 return NULL;
458 if (PyObject_SetAttrString(self, "args", args) ||
459 PyObject_SetAttrString(self, "errno", Py_None) ||
460 PyObject_SetAttrString(self, "strerror", Py_None) ||
461 PyObject_SetAttrString(self, "filename", Py_None))
463 goto finally;
466 switch (PySequence_Size(args)) {
467 case 3:
468 /* Where a function has a single filename, such as open() or some
469 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
470 * called, giving a third argument which is the filename. But, so
471 * that old code using in-place unpacking doesn't break, e.g.:
473 * except IOError, (errno, strerror):
475 * we hack args so that it only contains two items. This also
476 * means we need our own __str__() which prints out the filename
477 * when it was supplied.
479 item0 = PySequence_GetItem(args, 0);
480 item1 = PySequence_GetItem(args, 1);
481 item2 = PySequence_GetItem(args, 2);
482 if (!item0 || !item1 || !item2)
483 goto finally;
485 if (PyObject_SetAttrString(self, "errno", item0) ||
486 PyObject_SetAttrString(self, "strerror", item1) ||
487 PyObject_SetAttrString(self, "filename", item2))
489 goto finally;
492 subslice = PySequence_GetSlice(args, 0, 2);
493 if (!subslice || PyObject_SetAttrString(self, "args", subslice))
494 goto finally;
495 break;
497 case 2:
498 /* Used when PyErr_SetFromErrno() is called and no filename
499 * argument is given.
501 item0 = PySequence_GetItem(args, 0);
502 item1 = PySequence_GetItem(args, 1);
503 if (!item0 || !item1)
504 goto finally;
506 if (PyObject_SetAttrString(self, "errno", item0) ||
507 PyObject_SetAttrString(self, "strerror", item1))
509 goto finally;
511 break;
514 Py_INCREF(Py_None);
515 rtnval = Py_None;
517 finally:
518 Py_DECREF(args);
519 Py_XDECREF(item0);
520 Py_XDECREF(item1);
521 Py_XDECREF(item2);
522 Py_XDECREF(subslice);
523 return rtnval;
527 static PyObject *
528 EnvironmentError__str__(PyObject *self, PyObject *args)
530 PyObject *originalself = self;
531 PyObject *filename;
532 PyObject *serrno;
533 PyObject *strerror;
534 PyObject *rtnval = NULL;
536 if (!PyArg_ParseTuple(args, "O:__str__", &self))
537 return NULL;
539 filename = PyObject_GetAttrString(self, "filename");
540 serrno = PyObject_GetAttrString(self, "errno");
541 strerror = PyObject_GetAttrString(self, "strerror");
542 if (!filename || !serrno || !strerror)
543 goto finally;
545 if (filename != Py_None) {
546 PyObject *fmt = PyString_FromString("[Errno %s] %s: %s");
547 PyObject *repr = PyObject_Repr(filename);
548 PyObject *tuple = PyTuple_New(3);
550 if (!fmt || !repr || !tuple) {
551 Py_XDECREF(fmt);
552 Py_XDECREF(repr);
553 Py_XDECREF(tuple);
554 goto finally;
557 PyTuple_SET_ITEM(tuple, 0, serrno);
558 PyTuple_SET_ITEM(tuple, 1, strerror);
559 PyTuple_SET_ITEM(tuple, 2, repr);
561 rtnval = PyString_Format(fmt, tuple);
563 Py_DECREF(fmt);
564 Py_DECREF(tuple);
565 /* already freed because tuple owned only reference */
566 serrno = NULL;
567 strerror = NULL;
569 else if (PyObject_IsTrue(serrno) && PyObject_IsTrue(strerror)) {
570 PyObject *fmt = PyString_FromString("[Errno %s] %s");
571 PyObject *tuple = PyTuple_New(2);
573 if (!fmt || !tuple) {
574 Py_XDECREF(fmt);
575 Py_XDECREF(tuple);
576 goto finally;
579 PyTuple_SET_ITEM(tuple, 0, serrno);
580 PyTuple_SET_ITEM(tuple, 1, strerror);
582 rtnval = PyString_Format(fmt, tuple);
584 Py_DECREF(fmt);
585 Py_DECREF(tuple);
586 /* already freed because tuple owned only reference */
587 serrno = NULL;
588 strerror = NULL;
590 else
591 /* The original Python code said:
593 * return StandardError.__str__(self)
595 * but there is no StandardError__str__() function; we happen to
596 * know that's just a pass through to Exception__str__().
598 rtnval = Exception__str__(originalself, args);
600 finally:
601 Py_XDECREF(filename);
602 Py_XDECREF(serrno);
603 Py_XDECREF(strerror);
604 return rtnval;
608 static
609 PyMethodDef EnvironmentError_methods[] = {
610 {"__init__", EnvironmentError__init__, METH_VARARGS},
611 {"__str__", EnvironmentError__str__, METH_VARARGS},
612 {NULL, NULL}
618 static char
619 IOError__doc__[] = "I/O operation failed.";
621 static char
622 OSError__doc__[] = "OS system call failed.";
624 #ifdef MS_WINDOWS
625 static char
626 WindowsError__doc__[] = "MS-Windows OS system call failed.";
627 #endif /* MS_WINDOWS */
629 static char
630 EOFError__doc__[] = "Read beyond end of file.";
632 static char
633 RuntimeError__doc__[] = "Unspecified run-time error.";
635 static char
636 NotImplementedError__doc__[] =
637 "Method or function hasn't been implemented yet.";
639 static char
640 NameError__doc__[] = "Name not found globally.";
642 static char
643 UnboundLocalError__doc__[] =
644 "Local name referenced but not bound to a value.";
646 static char
647 AttributeError__doc__[] = "Attribute not found.";
651 static char
652 SyntaxError__doc__[] = "Invalid syntax.";
655 static int
656 SyntaxError__classinit__(PyObject *klass)
658 int retval = 0;
659 PyObject *emptystring = PyString_FromString("");
661 /* Additional class-creation time initializations */
662 if (!emptystring ||
663 PyObject_SetAttrString(klass, "msg", emptystring) ||
664 PyObject_SetAttrString(klass, "filename", Py_None) ||
665 PyObject_SetAttrString(klass, "lineno", Py_None) ||
666 PyObject_SetAttrString(klass, "offset", Py_None) ||
667 PyObject_SetAttrString(klass, "text", Py_None))
669 retval = -1;
671 Py_XDECREF(emptystring);
672 return retval;
676 static PyObject *
677 SyntaxError__init__(PyObject *self, PyObject *args)
679 PyObject *rtnval = NULL;
680 int lenargs;
682 if (!(self = get_self(args)))
683 return NULL;
685 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
686 return NULL;
688 if (PyObject_SetAttrString(self, "args", args))
689 goto finally;
691 lenargs = PySequence_Size(args);
692 if (lenargs >= 1) {
693 PyObject *item0 = PySequence_GetItem(args, 0);
694 int status;
696 if (!item0)
697 goto finally;
698 status = PyObject_SetAttrString(self, "msg", item0);
699 Py_DECREF(item0);
700 if (status)
701 goto finally;
703 if (lenargs == 2) {
704 PyObject *info = PySequence_GetItem(args, 1);
705 PyObject *filename = NULL, *lineno = NULL;
706 PyObject *offset = NULL, *text = NULL;
707 int status = 1;
709 if (!info)
710 goto finally;
712 filename = PySequence_GetItem(info, 0);
713 if (filename != NULL) {
714 lineno = PySequence_GetItem(info, 1);
715 if (lineno != NULL) {
716 offset = PySequence_GetItem(info, 2);
717 if (offset != NULL) {
718 text = PySequence_GetItem(info, 3);
719 if (text != NULL) {
720 status =
721 PyObject_SetAttrString(self, "filename", filename)
722 || PyObject_SetAttrString(self, "lineno", lineno)
723 || PyObject_SetAttrString(self, "offset", offset)
724 || PyObject_SetAttrString(self, "text", text);
725 Py_DECREF(text);
727 Py_DECREF(offset);
729 Py_DECREF(lineno);
731 Py_DECREF(filename);
733 Py_DECREF(info);
735 if (status)
736 goto finally;
738 Py_INCREF(Py_None);
739 rtnval = Py_None;
741 finally:
742 Py_DECREF(args);
743 return rtnval;
747 /* This is called "my_basename" instead of just "basename" to avoid name
748 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
749 defined, and Python does define that. */
750 static char *
751 my_basename(char *name)
753 char *cp = name;
754 char *result = name;
756 if (name == NULL)
757 return "???";
758 while (*cp != '\0') {
759 if (*cp == SEP)
760 result = cp + 1;
761 ++cp;
763 return result;
767 static PyObject *
768 SyntaxError__str__(PyObject *self, PyObject *args)
770 PyObject *msg;
771 PyObject *str;
772 PyObject *filename, *lineno, *result;
774 if (!PyArg_ParseTuple(args, "O:__str__", &self))
775 return NULL;
777 if (!(msg = PyObject_GetAttrString(self, "msg")))
778 return NULL;
780 str = PyObject_Str(msg);
781 Py_DECREF(msg);
782 result = str;
784 /* XXX -- do all the additional formatting with filename and
785 lineno here */
787 if (PyString_Check(str)) {
788 int have_filename = 0;
789 int have_lineno = 0;
790 char *buffer = NULL;
792 if ((filename = PyObject_GetAttrString(self, "filename")) != NULL)
793 have_filename = PyString_Check(filename);
794 else
795 PyErr_Clear();
797 if ((lineno = PyObject_GetAttrString(self, "lineno")) != NULL)
798 have_lineno = PyInt_Check(lineno);
799 else
800 PyErr_Clear();
802 if (have_filename || have_lineno) {
803 int bufsize = PyString_GET_SIZE(str) + 64;
804 if (have_filename)
805 bufsize += PyString_GET_SIZE(filename);
807 buffer = PyMem_Malloc(bufsize);
808 if (buffer != NULL) {
809 if (have_filename && have_lineno)
810 sprintf(buffer, "%s (%s, line %ld)",
811 PyString_AS_STRING(str),
812 my_basename(PyString_AS_STRING(filename)),
813 PyInt_AsLong(lineno));
814 else if (have_filename)
815 sprintf(buffer, "%s (%s)",
816 PyString_AS_STRING(str),
817 my_basename(PyString_AS_STRING(filename)));
818 else if (have_lineno)
819 sprintf(buffer, "%s (line %ld)",
820 PyString_AS_STRING(str),
821 PyInt_AsLong(lineno));
823 result = PyString_FromString(buffer);
824 PyMem_FREE(buffer);
826 if (result == NULL)
827 result = str;
828 else
829 Py_DECREF(str);
832 Py_XDECREF(filename);
833 Py_XDECREF(lineno);
835 return result;
839 PyMethodDef SyntaxError_methods[] = {
840 {"__init__", SyntaxError__init__, METH_VARARGS},
841 {"__str__", SyntaxError__str__, METH_VARARGS},
842 {NULL, NULL}
847 /* Exception doc strings */
849 static char
850 AssertionError__doc__[] = "Assertion failed.";
852 static char
853 LookupError__doc__[] = "Base class for lookup errors.";
855 static char
856 IndexError__doc__[] = "Sequence index out of range.";
858 static char
859 KeyError__doc__[] = "Mapping key not found.";
861 static char
862 ArithmeticError__doc__[] = "Base class for arithmetic errors.";
864 static char
865 OverflowError__doc__[] = "Result too large to be represented.";
867 static char
868 ZeroDivisionError__doc__[] =
869 "Second argument to a division or modulo operation was zero.";
871 static char
872 FloatingPointError__doc__[] = "Floating point operation failed.";
874 static char
875 ValueError__doc__[] = "Inappropriate argument value (of correct type).";
877 static char
878 UnicodeError__doc__[] = "Unicode related error.";
880 static char
881 SystemError__doc__[] = "Internal error in the Python interpreter.\n\
883 Please report this to the Python maintainer, along with the traceback,\n\
884 the Python version, and the hardware/OS platform and version.";
886 static char
887 MemoryError__doc__[] = "Out of memory.";
889 static char
890 IndentationError__doc__[] = "Improper indentation.";
892 static char
893 TabError__doc__[] = "Improper mixture of spaces and tabs.";
895 /* Warning category docstrings */
897 static char
898 Warning__doc__[] = "Base class for warning categories.";
900 static char
901 UserWarning__doc__[] = "Base class for warnings generated by user code.";
903 static char
904 DeprecationWarning__doc__[] =
905 "Base class for warnings about deprecated features.";
907 static char
908 SyntaxWarning__doc__[] = "Base class for warnings about dubious syntax.";
910 static char
911 RuntimeWarning__doc__[] =
912 "Base class for warnings about dubious runtime behavior.";
916 /* module global functions */
917 static PyMethodDef functions[] = {
918 /* Sentinel */
919 {NULL, NULL}
924 /* Global C API defined exceptions */
926 PyObject *PyExc_Exception;
927 PyObject *PyExc_StandardError;
928 PyObject *PyExc_ArithmeticError;
929 PyObject *PyExc_LookupError;
931 PyObject *PyExc_AssertionError;
932 PyObject *PyExc_AttributeError;
933 PyObject *PyExc_EOFError;
934 PyObject *PyExc_FloatingPointError;
935 PyObject *PyExc_EnvironmentError;
936 PyObject *PyExc_IOError;
937 PyObject *PyExc_OSError;
938 PyObject *PyExc_ImportError;
939 PyObject *PyExc_IndexError;
940 PyObject *PyExc_KeyError;
941 PyObject *PyExc_KeyboardInterrupt;
942 PyObject *PyExc_MemoryError;
943 PyObject *PyExc_NameError;
944 PyObject *PyExc_OverflowError;
945 PyObject *PyExc_RuntimeError;
946 PyObject *PyExc_NotImplementedError;
947 PyObject *PyExc_SyntaxError;
948 PyObject *PyExc_IndentationError;
949 PyObject *PyExc_TabError;
950 PyObject *PyExc_SystemError;
951 PyObject *PyExc_SystemExit;
952 PyObject *PyExc_UnboundLocalError;
953 PyObject *PyExc_UnicodeError;
954 PyObject *PyExc_TypeError;
955 PyObject *PyExc_ValueError;
956 PyObject *PyExc_ZeroDivisionError;
957 #ifdef MS_WINDOWS
958 PyObject *PyExc_WindowsError;
959 #endif
961 /* Pre-computed MemoryError instance. Best to create this as early as
962 * possibly and not wait until a MemoryError is actually raised!
964 PyObject *PyExc_MemoryErrorInst;
966 /* Predefined warning categories */
967 PyObject *PyExc_Warning;
968 PyObject *PyExc_UserWarning;
969 PyObject *PyExc_DeprecationWarning;
970 PyObject *PyExc_SyntaxWarning;
971 PyObject *PyExc_RuntimeWarning;
975 /* mapping between exception names and their PyObject ** */
976 static struct {
977 char *name;
978 PyObject **exc;
979 PyObject **base; /* NULL == PyExc_StandardError */
980 char *docstr;
981 PyMethodDef *methods;
982 int (*classinit)(PyObject *);
983 } exctable[] = {
985 * The first three classes MUST appear in exactly this order
987 {"Exception", &PyExc_Exception},
988 {"StandardError", &PyExc_StandardError, &PyExc_Exception,
989 StandardError__doc__},
990 {"TypeError", &PyExc_TypeError, 0, TypeError__doc__},
992 * The rest appear in depth-first order of the hierarchy
994 {"SystemExit", &PyExc_SystemExit, &PyExc_Exception, SystemExit__doc__,
995 SystemExit_methods},
996 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 0, KeyboardInterrupt__doc__},
997 {"ImportError", &PyExc_ImportError, 0, ImportError__doc__},
998 {"EnvironmentError", &PyExc_EnvironmentError, 0, EnvironmentError__doc__,
999 EnvironmentError_methods},
1000 {"IOError", &PyExc_IOError, &PyExc_EnvironmentError, IOError__doc__},
1001 {"OSError", &PyExc_OSError, &PyExc_EnvironmentError, OSError__doc__},
1002 #ifdef MS_WINDOWS
1003 {"WindowsError", &PyExc_WindowsError, &PyExc_OSError,
1004 WindowsError__doc__},
1005 #endif /* MS_WINDOWS */
1006 {"EOFError", &PyExc_EOFError, 0, EOFError__doc__},
1007 {"RuntimeError", &PyExc_RuntimeError, 0, RuntimeError__doc__},
1008 {"NotImplementedError", &PyExc_NotImplementedError,
1009 &PyExc_RuntimeError, NotImplementedError__doc__},
1010 {"NameError", &PyExc_NameError, 0, NameError__doc__},
1011 {"UnboundLocalError", &PyExc_UnboundLocalError, &PyExc_NameError,
1012 UnboundLocalError__doc__},
1013 {"AttributeError", &PyExc_AttributeError, 0, AttributeError__doc__},
1014 {"SyntaxError", &PyExc_SyntaxError, 0, SyntaxError__doc__,
1015 SyntaxError_methods, SyntaxError__classinit__},
1016 {"IndentationError", &PyExc_IndentationError, &PyExc_SyntaxError,
1017 IndentationError__doc__},
1018 {"TabError", &PyExc_TabError, &PyExc_IndentationError,
1019 TabError__doc__},
1020 {"AssertionError", &PyExc_AssertionError, 0, AssertionError__doc__},
1021 {"LookupError", &PyExc_LookupError, 0, LookupError__doc__},
1022 {"IndexError", &PyExc_IndexError, &PyExc_LookupError,
1023 IndexError__doc__},
1024 {"KeyError", &PyExc_KeyError, &PyExc_LookupError,
1025 KeyError__doc__},
1026 {"ArithmeticError", &PyExc_ArithmeticError, 0, ArithmeticError__doc__},
1027 {"OverflowError", &PyExc_OverflowError, &PyExc_ArithmeticError,
1028 OverflowError__doc__},
1029 {"ZeroDivisionError", &PyExc_ZeroDivisionError, &PyExc_ArithmeticError,
1030 ZeroDivisionError__doc__},
1031 {"FloatingPointError", &PyExc_FloatingPointError, &PyExc_ArithmeticError,
1032 FloatingPointError__doc__},
1033 {"ValueError", &PyExc_ValueError, 0, ValueError__doc__},
1034 {"UnicodeError", &PyExc_UnicodeError, &PyExc_ValueError, UnicodeError__doc__},
1035 {"SystemError", &PyExc_SystemError, 0, SystemError__doc__},
1036 {"MemoryError", &PyExc_MemoryError, 0, MemoryError__doc__},
1037 /* Warning categories */
1038 {"Warning", &PyExc_Warning, &PyExc_Exception, Warning__doc__},
1039 {"UserWarning", &PyExc_UserWarning, &PyExc_Warning, UserWarning__doc__},
1040 {"DeprecationWarning", &PyExc_DeprecationWarning, &PyExc_Warning,
1041 DeprecationWarning__doc__},
1042 {"SyntaxWarning", &PyExc_SyntaxWarning, &PyExc_Warning, SyntaxWarning__doc__},
1043 {"RuntimeWarning", &PyExc_RuntimeWarning, &PyExc_Warning,
1044 RuntimeWarning__doc__},
1045 /* Sentinel */
1046 {NULL}
1051 DL_EXPORT(void)
1052 init_exceptions(void)
1054 char *modulename = "exceptions";
1055 int modnamesz = strlen(modulename);
1056 int i;
1058 PyObject *me = Py_InitModule(modulename, functions);
1059 PyObject *mydict = PyModule_GetDict(me);
1060 PyObject *bltinmod = PyImport_ImportModule("__builtin__");
1061 PyObject *bdict = PyModule_GetDict(bltinmod);
1062 PyObject *doc = PyString_FromString(module__doc__);
1063 PyObject *args;
1065 PyDict_SetItemString(mydict, "__doc__", doc);
1066 Py_DECREF(doc);
1067 if (PyErr_Occurred())
1068 Py_FatalError("exceptions bootstrapping error.");
1070 /* This is the base class of all exceptions, so make it first. */
1071 if (make_Exception(modulename) ||
1072 PyDict_SetItemString(mydict, "Exception", PyExc_Exception) ||
1073 PyDict_SetItemString(bdict, "Exception", PyExc_Exception))
1075 Py_FatalError("Base class `Exception' could not be created.");
1078 /* Now we can programmatically create all the remaining exceptions.
1079 * Remember to start the loop at 1 to skip Exceptions.
1081 for (i=1; exctable[i].name; i++) {
1082 int status;
1083 char *cname = PyMem_NEW(char, modnamesz+strlen(exctable[i].name)+2);
1084 PyObject *base;
1086 (void)strcpy(cname, modulename);
1087 (void)strcat(cname, ".");
1088 (void)strcat(cname, exctable[i].name);
1090 if (exctable[i].base == 0)
1091 base = PyExc_StandardError;
1092 else
1093 base = *exctable[i].base;
1095 status = make_class(exctable[i].exc, base, cname,
1096 exctable[i].methods,
1097 exctable[i].docstr);
1099 PyMem_DEL(cname);
1101 if (status)
1102 Py_FatalError("Standard exception classes could not be created.");
1104 if (exctable[i].classinit) {
1105 status = (*exctable[i].classinit)(*exctable[i].exc);
1106 if (status)
1107 Py_FatalError("An exception class could not be initialized.");
1110 /* Now insert the class into both this module and the __builtin__
1111 * module.
1113 if (PyDict_SetItemString(mydict, exctable[i].name, *exctable[i].exc) ||
1114 PyDict_SetItemString(bdict, exctable[i].name, *exctable[i].exc))
1116 Py_FatalError("Module dictionary insertion problem.");
1120 /* Now we need to pre-allocate a MemoryError instance */
1121 args = Py_BuildValue("()");
1122 if (!args ||
1123 !(PyExc_MemoryErrorInst = PyEval_CallObject(PyExc_MemoryError, args)))
1125 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
1127 Py_DECREF(args);
1129 /* We're done with __builtin__ */
1130 Py_DECREF(bltinmod);
1134 DL_EXPORT(void)
1135 fini_exceptions(void)
1137 int i;
1139 Py_XDECREF(PyExc_MemoryErrorInst);
1140 PyExc_MemoryErrorInst = NULL;
1142 for (i=0; exctable[i].name; i++) {
1143 /* clear the class's dictionary, freeing up circular references
1144 * between the class and its methods.
1146 PyObject* cdict = PyObject_GetAttrString(*exctable[i].exc, "__dict__");
1147 PyDict_Clear(cdict);
1148 Py_DECREF(cdict);
1150 /* Now decref the exception class */
1151 Py_XDECREF(*exctable[i].exc);
1152 *exctable[i].exc = NULL;