blob: c0e4d5464bc86879902d132bd6efa531a5f7954b [file] [log] [blame]
Barry Warsaw675ac282000-05-26 19:05:16 +00001/* 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.
6 *
7 * By moving the exceptions into C and statically linking, we can guarantee
8 * that the standard exceptions will always be available.
9 *
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
14 *
15 * written by Fredrik Lundh
16 * modifications, additions, cleanups, and proofreading by Barry Warsaw
17 *
18 * Copyright (c) 1998-2000 by Secret Labs AB. All rights reserved.
19 */
20
21#include "Python.h"
22
Tim Petersbf26e072000-07-12 04:02:10 +000023/* Caution: MS Visual C++ 6 errors if a single string literal exceeds
24 * 2Kb. So the module docstring has been broken roughly in half, using
25 * compile-time literal concatenation.
26 */
Barry Warsaw675ac282000-05-26 19:05:16 +000027static char
28module__doc__[] =
29"Python's standard exception class hierarchy.\n\
30\n\
31Before Python 1.5, the standard exceptions were all simple string objects.\n\
32In Python 1.5, the standard exceptions were converted to classes organized\n\
33into a relatively flat hierarchy. String-based standard exceptions were\n\
34optional, or used as a fallback if some problem occurred while importing\n\
35the exception module. With Python 1.6, optional string-based standard\n\
36exceptions were removed (along with the -X command line flag).\n\
37\n\
38The class exceptions were implemented in such a way as to be almost\n\
39completely backward compatible. Some tricky uses of IOError could\n\
40potentially have broken, but by Python 1.6, all of these should have\n\
41been fixed. As of Python 1.6, the class-based standard exceptions are\n\
42now implemented in C, and are guaranteed to exist in the Python\n\
43interpreter.\n\
44\n\
45Here is a rundown of the class hierarchy. The classes found here are\n\
46inserted into both the exceptions module and the `built-in' module. It is\n\
47recommended that user defined class based exceptions be derived from the\n\
Tim Petersbf26e072000-07-12 04:02:10 +000048`Exception' class, although this is currently not enforced.\n"
49 /* keep string pieces "small" */
50"\n\
Barry Warsaw675ac282000-05-26 19:05:16 +000051Exception\n\
52 |\n\
53 +-- SystemExit\n\
54 +-- StandardError\n\
55 |\n\
56 +-- KeyboardInterrupt\n\
57 +-- ImportError\n\
58 +-- EnvironmentError\n\
59 | |\n\
60 | +-- IOError\n\
61 | +-- OSError\n\
62 | |\n\
63 | +-- WindowsError\n\
64 |\n\
65 +-- EOFError\n\
66 +-- RuntimeError\n\
67 | |\n\
68 | +-- NotImplementedError\n\
69 |\n\
70 +-- NameError\n\
71 | |\n\
72 | +-- UnboundLocalError\n\
73 |\n\
74 +-- AttributeError\n\
75 +-- SyntaxError\n\
Fred Drake85f36392000-07-11 17:53:00 +000076 | |\n\
77 | +-- IndentationError\n\
78 | |\n\
79 | +-- TabError\n\
80 |\n\
Barry Warsaw675ac282000-05-26 19:05:16 +000081 +-- TypeError\n\
82 +-- AssertionError\n\
83 +-- LookupError\n\
84 | |\n\
85 | +-- IndexError\n\
86 | +-- KeyError\n\
87 |\n\
88 +-- ArithmeticError\n\
89 | |\n\
90 | +-- OverflowError\n\
91 | +-- ZeroDivisionError\n\
92 | +-- FloatingPointError\n\
93 |\n\
94 +-- ValueError\n\
95 | |\n\
96 | +-- UnicodeError\n\
97 |\n\
98 +-- SystemError\n\
99 +-- MemoryError";
100
101
102/* Helper function for populating a dictionary with method wrappers. */
103static int
104populate_methods(PyObject* klass, PyObject* dict, PyMethodDef* methods)
105{
106 if (!methods)
107 return 0;
108
109 while (methods->ml_name) {
110 /* get a wrapper for the built-in function */
111 PyObject* func = PyCFunction_New(methods, NULL);
112 PyObject* meth;
113 int status;
114
115 if (!func)
116 return -1;
117
118 /* turn the function into an unbound method */
119 if (!(meth = PyMethod_New(func, NULL, klass))) {
120 Py_DECREF(func);
121 return -1;
122 }
123
124 /* add method to dictionary */
125 status = PyDict_SetItemString(dict, methods->ml_name, meth);
126 Py_DECREF(meth);
127 Py_DECREF(func);
128
129 /* stop now if an error occurred, otherwise do the next method */
130 if (status)
131 return status;
132
133 methods++;
134 }
135 return 0;
136}
137
138
139
140/* This function is used to create all subsequent exception classes. */
141static int
142make_class(PyObject** klass, PyObject* base,
143 char* name, PyMethodDef* methods,
144 char* docstr)
145{
146 PyObject* dict = PyDict_New();
147 PyObject* str = NULL;
148 int status = -1;
149
150 if (!dict)
151 return -1;
152
153 /* If an error occurs from here on, goto finally instead of explicitly
154 * returning NULL.
155 */
156
157 if (docstr) {
158 if (!(str = PyString_FromString(docstr)))
159 goto finally;
160 if (PyDict_SetItemString(dict, "__doc__", str))
161 goto finally;
162 }
163
164 if (!(*klass = PyErr_NewException(name, base, dict)))
165 goto finally;
166
167 if (populate_methods(*klass, dict, methods)) {
168 Py_DECREF(*klass);
169 *klass = NULL;
170 }
171
172 status = 0;
173
174 finally:
175 Py_XDECREF(dict);
176 Py_XDECREF(str);
177 return status;
178}
179
180
181/* Use this for *args signatures, otherwise just use PyArg_ParseTuple() */
182static PyObject* get_self(PyObject* args)
183{
184 PyObject* self = PyTuple_GetItem(args, 0);
185 if (!self) {
186 /* Watch out for being called to early in the bootstapping process */
187 if (PyExc_TypeError) {
188 PyErr_SetString(PyExc_TypeError,
189 "unbound method must be called with class instance 1st argument");
190 }
191 return NULL;
192 }
193 return self;
194}
195
196
197
198/* Notes on bootstrapping the exception classes.
199 *
200 * First thing we create is the base class for all exceptions, called
201 * appropriately enough: Exception. Creation of this class makes no
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000202 * assumptions about the existence of any other exception class -- except
Barry Warsaw675ac282000-05-26 19:05:16 +0000203 * for TypeError, which can conditionally exist.
204 *
205 * Next, StandardError is created (which is quite simple) followed by
206 * TypeError, because the instantiation of other exceptions can potentially
207 * throw a TypeError. Once these exceptions are created, all the others
208 * can be created in any order. See the static exctable below for the
209 * explicit bootstrap order.
210 *
211 * All classes after Exception can be created using PyErr_NewException().
212 */
213
214static char
215Exception__doc__[] = "Common base class for all exceptions.";
216
217
218static PyObject*
219Exception__init__(PyObject* self, PyObject* args)
220{
221 int status;
222
223 if (!(self = get_self(args)))
224 return NULL;
225
226 /* set args attribute */
227 args = PySequence_GetSlice(args, 1, PySequence_Length(args));
228 if (!args)
229 return NULL;
230 status = PyObject_SetAttrString(self, "args", args);
231 Py_DECREF(args);
232 if (status < 0)
233 return NULL;
234
235 Py_INCREF(Py_None);
236 return Py_None;
237}
238
239
240static PyObject*
241Exception__str__(PyObject* self, PyObject* args)
242{
243 PyObject* out;
Barry Warsaw675ac282000-05-26 19:05:16 +0000244
245 if (!PyArg_ParseTuple(args, "O", &self))
246 return NULL;
247
248 args = PyObject_GetAttrString(self, "args");
249 if (!args)
250 return NULL;
251
252 switch (PySequence_Length(args)) {
253 case 0:
254 out = PyString_FromString("");
255 break;
256 case 1:
Barry Warsawb7816552000-07-09 22:27:10 +0000257 {
258 PyObject* tmp = PySequence_GetItem(args, 0);
259 if (tmp) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000260 out = PyObject_Str(tmp);
Barry Warsawb7816552000-07-09 22:27:10 +0000261 Py_DECREF(tmp);
262 }
263 else
264 out = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000265 break;
Barry Warsawb7816552000-07-09 22:27:10 +0000266 }
Barry Warsaw675ac282000-05-26 19:05:16 +0000267 default:
268 out = PyObject_Str(args);
269 break;
270 }
271
272 Py_DECREF(args);
273 return out;
274}
275
276
277static PyObject*
278Exception__getitem__(PyObject* self, PyObject* args)
279{
280 PyObject* out;
281 PyObject* index;
282
283 if (!PyArg_ParseTuple(args, "OO", &self, &index))
284 return NULL;
285
286 args = PyObject_GetAttrString(self, "args");
287 if (!args)
288 return NULL;
289
290 out = PyObject_GetItem(args, index);
291 Py_DECREF(args);
292 return out;
293}
294
295
296static PyMethodDef
297Exception_methods[] = {
298 /* methods for the Exception class */
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000299 { "__getitem__", Exception__getitem__, METH_VARARGS},
300 { "__str__", Exception__str__, METH_VARARGS},
301 { "__init__", Exception__init__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000302 { NULL, NULL }
303};
304
305
306static int
307make_Exception(char* modulename)
308{
309 PyObject* dict = PyDict_New();
310 PyObject* str = NULL;
311 PyObject* name = NULL;
312 int status = -1;
313
314 if (!dict)
315 return -1;
316
317 /* If an error occurs from here on, goto finally instead of explicitly
318 * returning NULL.
319 */
320
321 if (!(str = PyString_FromString(modulename)))
322 goto finally;
323 if (PyDict_SetItemString(dict, "__module__", str))
324 goto finally;
325 Py_DECREF(str);
326 if (!(str = PyString_FromString(Exception__doc__)))
327 goto finally;
328 if (PyDict_SetItemString(dict, "__doc__", str))
329 goto finally;
330
331 if (!(name = PyString_FromString("Exception")))
332 goto finally;
333
334 if (!(PyExc_Exception = PyClass_New(NULL, dict, name)))
335 goto finally;
336
337 /* Now populate the dictionary with the method suite */
338 if (populate_methods(PyExc_Exception, dict, Exception_methods))
339 /* Don't need to reclaim PyExc_Exception here because that'll
340 * happen during interpreter shutdown.
341 */
342 goto finally;
343
344 status = 0;
345
346 finally:
347 Py_XDECREF(dict);
348 Py_XDECREF(str);
349 Py_XDECREF(name);
350 return status;
351}
352
353
354
355static char
356StandardError__doc__[] = "Base class for all standard Python exceptions.";
357
358static char
359TypeError__doc__[] = "Inappropriate argument type.";
360
361
362
363static char
364SystemExit__doc__[] = "Request to exit from the interpreter.";
365
366
367static PyObject*
368SystemExit__init__(PyObject* self, PyObject* args)
369{
370 PyObject* code;
371 int status;
372
373 if (!(self = get_self(args)))
374 return NULL;
375
376 /* Set args attribute. */
377 if (!(args = PySequence_GetSlice(args, 1, PySequence_Length(args))))
378 return NULL;
379
380 status = PyObject_SetAttrString(self, "args", args);
381 if (status < 0) {
382 Py_DECREF(args);
383 return NULL;
384 }
385
386 /* set code attribute */
387 switch (PySequence_Length(args)) {
388 case 0:
389 Py_INCREF(Py_None);
390 code = Py_None;
391 break;
392 case 1:
393 code = PySequence_GetItem(args, 0);
394 break;
395 default:
396 Py_INCREF(args);
397 code = args;
398 break;
399 }
400
401 status = PyObject_SetAttrString(self, "code", code);
402 Py_DECREF(code);
403 Py_DECREF(args);
404 if (status < 0)
405 return NULL;
406
407 Py_INCREF(Py_None);
408 return Py_None;
409}
410
411
412PyMethodDef SystemExit_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000413 { "__init__", SystemExit__init__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000414 {NULL, NULL}
415};
416
417
418
419static char
420KeyboardInterrupt__doc__[] = "Program interrupted by user.";
421
422static char
423ImportError__doc__[] =
424"Import can't find module, or can't find name in module.";
425
426
427
428static char
429EnvironmentError__doc__[] = "Base class for I/O related errors.";
430
431
432static PyObject*
433EnvironmentError__init__(PyObject* self, PyObject* args)
434{
435 PyObject* item0 = NULL;
436 PyObject* item1 = NULL;
437 PyObject* item2 = NULL;
438 PyObject* subslice = NULL;
439 PyObject* rtnval = NULL;
440
441 if (!(self = get_self(args)))
442 return NULL;
443
444 if (!(args = PySequence_GetSlice(args, 1, PySequence_Length(args))))
445 return NULL;
446
447 if (PyObject_SetAttrString(self, "args", args) ||
448 PyObject_SetAttrString(self, "errno", Py_None) ||
449 PyObject_SetAttrString(self, "strerror", Py_None) ||
450 PyObject_SetAttrString(self, "filename", Py_None))
451 {
452 goto finally;
453 }
454
455 switch (PySequence_Length(args)) {
456 case 3:
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000457 /* Where a function has a single filename, such as open() or some
458 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
459 * called, giving a third argument which is the filename. But, so
460 * that old code using in-place unpacking doesn't break, e.g.:
Barry Warsaw675ac282000-05-26 19:05:16 +0000461 *
462 * except IOError, (errno, strerror):
463 *
464 * we hack args so that it only contains two items. This also
465 * means we need our own __str__() which prints out the filename
466 * when it was supplied.
467 */
468 item0 = PySequence_GetItem(args, 0);
469 item1 = PySequence_GetItem(args, 1);
470 item2 = PySequence_GetItem(args, 2);
471 if (!item0 || !item1 || !item2)
472 goto finally;
473
474 if (PyObject_SetAttrString(self, "errno", item0) ||
475 PyObject_SetAttrString(self, "strerror", item1) ||
476 PyObject_SetAttrString(self, "filename", item2))
477 {
478 goto finally;
479 }
480
481 subslice = PySequence_GetSlice(args, 0, 2);
482 if (!subslice || PyObject_SetAttrString(self, "args", subslice))
483 goto finally;
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000484 break;
Barry Warsaw675ac282000-05-26 19:05:16 +0000485
486 case 2:
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000487 /* Used when PyErr_SetFromErrno() is called and no filename
488 * argument is given.
489 */
Barry Warsaw675ac282000-05-26 19:05:16 +0000490 item0 = PySequence_GetItem(args, 0);
491 item1 = PySequence_GetItem(args, 1);
492 if (!item0 || !item1)
493 goto finally;
494
495 if (PyObject_SetAttrString(self, "errno", item0) ||
496 PyObject_SetAttrString(self, "strerror", item1))
497 {
498 goto finally;
499 }
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000500 break;
Barry Warsaw675ac282000-05-26 19:05:16 +0000501 }
502
503 Py_INCREF(Py_None);
504 rtnval = Py_None;
505
506 finally:
507 Py_DECREF(args);
508 Py_XDECREF(item0);
509 Py_XDECREF(item1);
510 Py_XDECREF(item2);
511 Py_XDECREF(subslice);
512 return rtnval;
513}
514
515
516static PyObject*
517EnvironmentError__str__(PyObject* self, PyObject* args)
518{
519 PyObject* originalself = self;
520 PyObject* filename;
521 PyObject* serrno;
522 PyObject* strerror;
523 PyObject* rtnval = NULL;
524
525 if (!PyArg_ParseTuple(args, "O", &self))
526 return NULL;
527
528 filename = PyObject_GetAttrString(self, "filename");
529 serrno = PyObject_GetAttrString(self, "errno");
530 strerror = PyObject_GetAttrString(self, "strerror");
531 if (!filename || !serrno || !strerror)
532 goto finally;
533
534 if (filename != Py_None) {
535 PyObject* fmt = PyString_FromString("[Errno %s] %s: %s");
536 PyObject* repr = PyObject_Repr(filename);
537 PyObject* tuple = PyTuple_New(3);
538
539 if (!fmt || !repr || !tuple) {
540 Py_XDECREF(fmt);
541 Py_XDECREF(repr);
542 Py_XDECREF(tuple);
543 goto finally;
544 }
545
546 PyTuple_SET_ITEM(tuple, 0, serrno);
547 PyTuple_SET_ITEM(tuple, 1, strerror);
548 PyTuple_SET_ITEM(tuple, 2, repr);
549
550 rtnval = PyString_Format(fmt, tuple);
551
552 Py_DECREF(fmt);
553 Py_DECREF(tuple);
554 /* already freed because tuple owned only reference */
555 serrno = NULL;
556 strerror = NULL;
557 }
558 else if (PyObject_IsTrue(serrno) && PyObject_IsTrue(strerror)) {
559 PyObject* fmt = PyString_FromString("[Errno %s] %s");
560 PyObject* tuple = PyTuple_New(2);
561
562 if (!fmt || !tuple) {
563 Py_XDECREF(fmt);
564 Py_XDECREF(tuple);
565 goto finally;
566 }
567
568 PyTuple_SET_ITEM(tuple, 0, serrno);
569 PyTuple_SET_ITEM(tuple, 1, strerror);
570
571 rtnval = PyString_Format(fmt, tuple);
572
573 Py_DECREF(fmt);
574 Py_DECREF(tuple);
575 /* already freed because tuple owned only reference */
576 serrno = NULL;
577 strerror = NULL;
578 }
579 else
580 /* The original Python code said:
581 *
582 * return StandardError.__str__(self)
583 *
584 * but there is no StandardError__str__() function; we happen to
585 * know that's just a pass through to Exception__str__().
586 */
587 rtnval = Exception__str__(originalself, args);
588
589 finally:
590 Py_XDECREF(filename);
591 Py_XDECREF(serrno);
592 Py_XDECREF(strerror);
593 return rtnval;
594}
595
596
597static
598PyMethodDef EnvironmentError_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000599 {"__init__", EnvironmentError__init__, METH_VARARGS},
600 {"__str__", EnvironmentError__str__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000601 {NULL, NULL}
602};
603
604
605
606
607static char
608IOError__doc__[] = "I/O operation failed.";
609
610static char
611OSError__doc__[] = "OS system call failed.";
612
613#ifdef MS_WINDOWS
614static char
615WindowsError__doc__[] = "MS-Windows OS system call failed.";
616#endif /* MS_WINDOWS */
617
618static char
619EOFError__doc__[] = "Read beyond end of file.";
620
621static char
622RuntimeError__doc__[] = "Unspecified run-time error.";
623
624static char
625NotImplementedError__doc__[] =
626"Method or function hasn't been implemented yet.";
627
628static char
629NameError__doc__[] = "Name not found globally.";
630
631static char
632UnboundLocalError__doc__[] =
633"Local name referenced but not bound to a value.";
634
635static char
636AttributeError__doc__[] = "Attribute not found.";
637
638
639
640static char
641SyntaxError__doc__[] = "Invalid syntax.";
642
643
644static int
645SyntaxError__classinit__(PyObject* klass)
646{
647 PyObject* emptystring = PyString_FromString("");
648
649 /* Additional class-creation time initializations */
650 if (!emptystring ||
651 PyObject_SetAttrString(klass, "msg", emptystring) ||
652 PyObject_SetAttrString(klass, "filename", Py_None) ||
653 PyObject_SetAttrString(klass, "lineno", Py_None) ||
654 PyObject_SetAttrString(klass, "offset", Py_None) ||
655 PyObject_SetAttrString(klass, "text", Py_None))
656 {
657 Py_XDECREF(emptystring);
658 return -1;
659 }
660 Py_DECREF(emptystring);
661 return 0;
662}
663
664
665static PyObject*
666SyntaxError__init__(PyObject* self, PyObject* args)
667{
668 PyObject* rtnval = NULL;
669 int lenargs;
670
671 if (!(self = get_self(args)))
672 return NULL;
673
674 if (!(args = PySequence_GetSlice(args, 1, PySequence_Length(args))))
675 return NULL;
676
677 if (PyObject_SetAttrString(self, "args", args))
678 goto finally;
679
680 lenargs = PySequence_Length(args);
681 if (lenargs >= 1) {
682 PyObject* item0 = PySequence_GetItem(args, 0);
683 int status;
684
685 if (!item0)
686 goto finally;
687 status = PyObject_SetAttrString(self, "msg", item0);
688 Py_DECREF(item0);
689 if (status)
690 goto finally;
691 }
692 if (lenargs == 2) {
693 PyObject* info = PySequence_GetItem(args, 1);
694 PyObject *filename, *lineno, *offset, *text;
695 int status = 1;
696
697 if (!info)
698 goto finally;
699
700 filename = PySequence_GetItem(info, 0);
701 lineno = PySequence_GetItem(info, 1);
702 offset = PySequence_GetItem(info, 2);
703 text = PySequence_GetItem(info, 3);
704
705 Py_DECREF(info);
706
707 if (filename && lineno && offset && text) {
708 status = PyObject_SetAttrString(self, "filename", filename) ||
709 PyObject_SetAttrString(self, "lineno", lineno) ||
710 PyObject_SetAttrString(self, "offset", offset) ||
711 PyObject_SetAttrString(self, "text", text);
712 }
713 Py_XDECREF(filename);
714 Py_XDECREF(lineno);
715 Py_XDECREF(offset);
716 Py_XDECREF(text);
717
718 if (status)
719 goto finally;
720 }
721 Py_INCREF(Py_None);
722 rtnval = Py_None;
723
724 finally:
725 Py_DECREF(args);
726 return rtnval;
727}
728
729
730static PyObject*
731SyntaxError__str__(PyObject* self, PyObject* args)
732{
733 PyObject* msg;
734 PyObject* str;
735
736 if (!PyArg_ParseTuple(args, "O", &self))
737 return NULL;
738
739 if (!(msg = PyObject_GetAttrString(self, "msg")))
740 return NULL;
741
742 str = PyObject_Str(msg);
743 Py_DECREF(msg);
744 return str;
745}
746
747
748PyMethodDef SyntaxError_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000749 {"__init__", SyntaxError__init__, METH_VARARGS},
750 {"__str__", SyntaxError__str__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000751 {NULL, NULL}
752};
753
754
755
756static char
757AssertionError__doc__[] = "Assertion failed.";
758
759static char
760LookupError__doc__[] = "Base class for lookup errors.";
761
762static char
763IndexError__doc__[] = "Sequence index out of range.";
764
765static char
766KeyError__doc__[] = "Mapping key not found.";
767
768static char
769ArithmeticError__doc__[] = "Base class for arithmetic errors.";
770
771static char
772OverflowError__doc__[] = "Result too large to be represented.";
773
774static char
775ZeroDivisionError__doc__[] =
776"Second argument to a division or modulo operation was zero.";
777
778static char
779FloatingPointError__doc__[] = "Floating point operation failed.";
780
781static char
782ValueError__doc__[] = "Inappropriate argument value (of correct type).";
783
784static char
785UnicodeError__doc__[] = "Unicode related error.";
786
787static char
788SystemError__doc__[] = "Internal error in the Python interpreter.\n\
789\n\
790Please report this to the Python maintainer, along with the traceback,\n\
791the Python version, and the hardware/OS platform and version.";
792
793static char
794MemoryError__doc__[] = "Out of memory.";
795
Fred Drake85f36392000-07-11 17:53:00 +0000796static char
797IndentationError__doc__[] = "Improper indentation.";
798
799static char
800TabError__doc__[] = "Improper mixture of spaces and tabs.";
801
Barry Warsaw675ac282000-05-26 19:05:16 +0000802
803
804/* module global functions */
805static PyMethodDef functions[] = {
806 /* Sentinel */
807 {NULL, NULL}
808};
809
810
811
812/* Global C API defined exceptions */
813
814PyObject *PyExc_Exception;
815PyObject *PyExc_StandardError;
816PyObject *PyExc_ArithmeticError;
817PyObject *PyExc_LookupError;
818
819PyObject *PyExc_AssertionError;
820PyObject *PyExc_AttributeError;
821PyObject *PyExc_EOFError;
822PyObject *PyExc_FloatingPointError;
823PyObject *PyExc_EnvironmentError;
824PyObject *PyExc_IOError;
825PyObject *PyExc_OSError;
826PyObject *PyExc_ImportError;
827PyObject *PyExc_IndexError;
828PyObject *PyExc_KeyError;
829PyObject *PyExc_KeyboardInterrupt;
830PyObject *PyExc_MemoryError;
831PyObject *PyExc_NameError;
832PyObject *PyExc_OverflowError;
833PyObject *PyExc_RuntimeError;
834PyObject *PyExc_NotImplementedError;
835PyObject *PyExc_SyntaxError;
Fred Drake85f36392000-07-11 17:53:00 +0000836PyObject *PyExc_IndentationError;
837PyObject *PyExc_TabError;
Barry Warsaw675ac282000-05-26 19:05:16 +0000838PyObject *PyExc_SystemError;
839PyObject *PyExc_SystemExit;
840PyObject *PyExc_UnboundLocalError;
841PyObject *PyExc_UnicodeError;
842PyObject *PyExc_TypeError;
843PyObject *PyExc_ValueError;
844PyObject *PyExc_ZeroDivisionError;
845#ifdef MS_WINDOWS
846PyObject *PyExc_WindowsError;
847#endif
848
849/* Pre-computed MemoryError instance. Best to create this as early as
850 * possibly and not wait until a MemoryError is actually raised!
851 */
852PyObject *PyExc_MemoryErrorInst;
853
854
855
856/* mapping between exception names and their PyObject** */
857static struct
858{
859 char* name;
860 PyObject** exc;
861 PyObject** base; /* NULL == PyExc_StandardError */
862 char* docstr;
863 PyMethodDef* methods;
864 int (*classinit)(PyObject*);
865}
866exctable[] = {
867 /*
868 * The first three classes MUST appear in exactly this order
869 */
870 {"Exception", &PyExc_Exception},
871 {"StandardError", &PyExc_StandardError, &PyExc_Exception,
872 StandardError__doc__},
873 {"TypeError", &PyExc_TypeError, 0, TypeError__doc__},
874 /*
875 * The rest appear in depth-first order of the hierarchy
876 */
877 {"SystemExit", &PyExc_SystemExit, &PyExc_Exception, SystemExit__doc__,
878 SystemExit_methods},
879 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 0, KeyboardInterrupt__doc__},
880 {"ImportError", &PyExc_ImportError, 0, ImportError__doc__},
881 {"EnvironmentError", &PyExc_EnvironmentError, 0, EnvironmentError__doc__,
882 EnvironmentError_methods},
883 {"IOError", &PyExc_IOError, &PyExc_EnvironmentError, IOError__doc__},
884 {"OSError", &PyExc_OSError, &PyExc_EnvironmentError, OSError__doc__},
885#ifdef MS_WINDOWS
886 {"WindowsError", &PyExc_WindowsError, &PyExc_EnvironmentError,
887 WindowsError__doc__},
888#endif /* MS_WINDOWS */
889 {"EOFError", &PyExc_EOFError, 0, EOFError__doc__},
890 {"RuntimeError", &PyExc_RuntimeError, 0, RuntimeError__doc__},
891 {"NotImplementedError", &PyExc_NotImplementedError,
892 &PyExc_RuntimeError, NotImplementedError__doc__},
893 {"NameError", &PyExc_NameError, 0, NameError__doc__},
894 {"UnboundLocalError", &PyExc_UnboundLocalError, &PyExc_NameError,
895 UnboundLocalError__doc__},
896 {"AttributeError", &PyExc_AttributeError, 0, AttributeError__doc__},
897 {"SyntaxError", &PyExc_SyntaxError, 0, SyntaxError__doc__,
898 SyntaxError_methods, SyntaxError__classinit__},
Fred Drake85f36392000-07-11 17:53:00 +0000899 {"IndentationError", &PyExc_IndentationError, &PyExc_SyntaxError,
900 IndentationError__doc__},
901 {"TabError", &PyExc_TabError, &PyExc_IndentationError,
902 TabError__doc__},
Barry Warsaw675ac282000-05-26 19:05:16 +0000903 {"AssertionError", &PyExc_AssertionError, 0, AssertionError__doc__},
904 {"LookupError", &PyExc_LookupError, 0, LookupError__doc__},
905 {"IndexError", &PyExc_IndexError, &PyExc_LookupError,
906 IndexError__doc__},
907 {"KeyError", &PyExc_KeyError, &PyExc_LookupError,
908 KeyError__doc__},
909 {"ArithmeticError", &PyExc_ArithmeticError, 0, ArithmeticError__doc__},
910 {"OverflowError", &PyExc_OverflowError, &PyExc_ArithmeticError,
911 OverflowError__doc__},
912 {"ZeroDivisionError", &PyExc_ZeroDivisionError, &PyExc_ArithmeticError,
913 ZeroDivisionError__doc__},
914 {"FloatingPointError", &PyExc_FloatingPointError, &PyExc_ArithmeticError,
915 FloatingPointError__doc__},
916 {"ValueError", &PyExc_ValueError, 0, ValueError__doc__},
917 {"UnicodeError", &PyExc_UnicodeError, &PyExc_ValueError, UnicodeError__doc__},
918 {"SystemError", &PyExc_SystemError, 0, SystemError__doc__},
919 {"MemoryError", &PyExc_MemoryError, 0, MemoryError__doc__},
920 /* Sentinel */
921 {NULL}
922};
923
924
925
926void
927#ifdef WIN32
928__declspec(dllexport)
929#endif /* WIN32 */
930init_exceptions()
931{
932 char* modulename = "exceptions";
933 int modnamesz = strlen(modulename);
934 int i;
935
936 PyObject* me = Py_InitModule(modulename, functions);
937 PyObject* mydict = PyModule_GetDict(me);
938 PyObject* bltinmod = PyImport_ImportModule("__builtin__");
939 PyObject* bdict = PyModule_GetDict(bltinmod);
940 PyObject* doc = PyString_FromString(module__doc__);
941 PyObject* args;
942
943 PyDict_SetItemString(mydict, "__doc__", doc);
Barry Warsaw8fcaa922000-07-01 04:45:52 +0000944 Py_DECREF(doc);
Barry Warsaw675ac282000-05-26 19:05:16 +0000945 if (PyErr_Occurred())
946 Py_FatalError("exceptions bootstrapping error.");
947
948 /* This is the base class of all exceptions, so make it first. */
949 if (make_Exception(modulename) ||
950 PyDict_SetItemString(mydict, "Exception", PyExc_Exception) ||
951 PyDict_SetItemString(bdict, "Exception", PyExc_Exception))
952 {
953 Py_FatalError("Base class `Exception' could not be created.");
954 }
955
956 /* Now we can programmatically create all the remaining exceptions.
957 * Remember to start the loop at 1 to skip Exceptions.
958 */
959 for (i=1; exctable[i].name; i++) {
960 int status;
961 char* cname = PyMem_NEW(char, modnamesz+strlen(exctable[i].name)+2);
962 PyObject* base;
963
964 (void)strcpy(cname, modulename);
965 (void)strcat(cname, ".");
966 (void)strcat(cname, exctable[i].name);
967
968 if (exctable[i].base == 0)
969 base = PyExc_StandardError;
970 else
971 base = *exctable[i].base;
972
973 status = make_class(exctable[i].exc, base, cname,
974 exctable[i].methods,
975 exctable[i].docstr);
976
977 PyMem_DEL(cname);
978
979 if (status)
980 Py_FatalError("Standard exception classes could not be created.");
981
982 if (exctable[i].classinit) {
983 status = (*exctable[i].classinit)(*exctable[i].exc);
984 if (status)
985 Py_FatalError("An exception class could not be initialized.");
986 }
987
988 /* Now insert the class into both this module and the __builtin__
989 * module.
990 */
991 if (PyDict_SetItemString(mydict, exctable[i].name, *exctable[i].exc) ||
992 PyDict_SetItemString(bdict, exctable[i].name, *exctable[i].exc))
993 {
994 Py_FatalError("Module dictionary insertion problem.");
995 }
996 }
997
998 /* Now we need to pre-allocate a MemoryError instance */
999 args = Py_BuildValue("()");
1000 if (!args ||
1001 !(PyExc_MemoryErrorInst = PyEval_CallObject(PyExc_MemoryError, args)))
1002 {
1003 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
1004 }
1005 Py_DECREF(args);
1006
1007 /* We're done with __builtin__ */
1008 Py_DECREF(bltinmod);
1009}
1010
1011
1012void
1013#ifdef WIN32
1014__declspec(dllexport)
1015#endif /* WIN32 */
1016fini_exceptions()
1017{
1018 int i;
1019
1020 Py_XDECREF(PyExc_MemoryErrorInst);
1021 PyExc_MemoryErrorInst = NULL;
1022
1023 for (i=0; exctable[i].name; i++) {
1024 Py_XDECREF(*exctable[i].exc);
1025 *exctable[i].exc = NULL;
1026 }
1027}