blob: b63daee18f7d5086daacea2fe4653e89ddf9bf40 [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) {
Thomas Wouters7e474022000-07-16 12:04:32 +0000186 /* Watch out for being called to early in the bootstrapping process */
Barry Warsaw675ac282000-05-26 19:05:16 +0000187 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 */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000227 /* XXX size is only a hint */
228 args = PySequence_GetSlice(args, 1, PySequence_Size(args));
Barry Warsaw675ac282000-05-26 19:05:16 +0000229 if (!args)
230 return NULL;
231 status = PyObject_SetAttrString(self, "args", args);
232 Py_DECREF(args);
233 if (status < 0)
234 return NULL;
235
236 Py_INCREF(Py_None);
237 return Py_None;
238}
239
240
241static PyObject*
242Exception__str__(PyObject* self, PyObject* args)
243{
244 PyObject* out;
Barry Warsaw675ac282000-05-26 19:05:16 +0000245
246 if (!PyArg_ParseTuple(args, "O", &self))
247 return NULL;
248
249 args = PyObject_GetAttrString(self, "args");
250 if (!args)
251 return NULL;
252
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000253 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000254 case 0:
255 out = PyString_FromString("");
256 break;
257 case 1:
Barry Warsawb7816552000-07-09 22:27:10 +0000258 {
259 PyObject* tmp = PySequence_GetItem(args, 0);
260 if (tmp) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000261 out = PyObject_Str(tmp);
Barry Warsawb7816552000-07-09 22:27:10 +0000262 Py_DECREF(tmp);
263 }
264 else
265 out = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000266 break;
Barry Warsawb7816552000-07-09 22:27:10 +0000267 }
Barry Warsaw675ac282000-05-26 19:05:16 +0000268 default:
269 out = PyObject_Str(args);
270 break;
271 }
272
273 Py_DECREF(args);
274 return out;
275}
276
277
278static PyObject*
279Exception__getitem__(PyObject* self, PyObject* args)
280{
281 PyObject* out;
282 PyObject* index;
283
284 if (!PyArg_ParseTuple(args, "OO", &self, &index))
285 return NULL;
286
287 args = PyObject_GetAttrString(self, "args");
288 if (!args)
289 return NULL;
290
291 out = PyObject_GetItem(args, index);
292 Py_DECREF(args);
293 return out;
294}
295
296
297static PyMethodDef
298Exception_methods[] = {
299 /* methods for the Exception class */
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000300 { "__getitem__", Exception__getitem__, METH_VARARGS},
301 { "__str__", Exception__str__, METH_VARARGS},
302 { "__init__", Exception__init__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000303 { NULL, NULL }
304};
305
306
307static int
308make_Exception(char* modulename)
309{
310 PyObject* dict = PyDict_New();
311 PyObject* str = NULL;
312 PyObject* name = NULL;
313 int status = -1;
314
315 if (!dict)
316 return -1;
317
318 /* If an error occurs from here on, goto finally instead of explicitly
319 * returning NULL.
320 */
321
322 if (!(str = PyString_FromString(modulename)))
323 goto finally;
324 if (PyDict_SetItemString(dict, "__module__", str))
325 goto finally;
326 Py_DECREF(str);
327 if (!(str = PyString_FromString(Exception__doc__)))
328 goto finally;
329 if (PyDict_SetItemString(dict, "__doc__", str))
330 goto finally;
331
332 if (!(name = PyString_FromString("Exception")))
333 goto finally;
334
335 if (!(PyExc_Exception = PyClass_New(NULL, dict, name)))
336 goto finally;
337
338 /* Now populate the dictionary with the method suite */
339 if (populate_methods(PyExc_Exception, dict, Exception_methods))
340 /* Don't need to reclaim PyExc_Exception here because that'll
341 * happen during interpreter shutdown.
342 */
343 goto finally;
344
345 status = 0;
346
347 finally:
348 Py_XDECREF(dict);
349 Py_XDECREF(str);
350 Py_XDECREF(name);
351 return status;
352}
353
354
355
356static char
357StandardError__doc__[] = "Base class for all standard Python exceptions.";
358
359static char
360TypeError__doc__[] = "Inappropriate argument type.";
361
362
363
364static char
365SystemExit__doc__[] = "Request to exit from the interpreter.";
366
367
368static PyObject*
369SystemExit__init__(PyObject* self, PyObject* args)
370{
371 PyObject* code;
372 int status;
373
374 if (!(self = get_self(args)))
375 return NULL;
376
377 /* Set args attribute. */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000378 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000379 return NULL;
380
381 status = PyObject_SetAttrString(self, "args", args);
382 if (status < 0) {
383 Py_DECREF(args);
384 return NULL;
385 }
386
387 /* set code attribute */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000388 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000389 case 0:
390 Py_INCREF(Py_None);
391 code = Py_None;
392 break;
393 case 1:
394 code = PySequence_GetItem(args, 0);
395 break;
396 default:
397 Py_INCREF(args);
398 code = args;
399 break;
400 }
401
402 status = PyObject_SetAttrString(self, "code", code);
403 Py_DECREF(code);
404 Py_DECREF(args);
405 if (status < 0)
406 return NULL;
407
408 Py_INCREF(Py_None);
409 return Py_None;
410}
411
412
413PyMethodDef SystemExit_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000414 { "__init__", SystemExit__init__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000415 {NULL, NULL}
416};
417
418
419
420static char
421KeyboardInterrupt__doc__[] = "Program interrupted by user.";
422
423static char
424ImportError__doc__[] =
425"Import can't find module, or can't find name in module.";
426
427
428
429static char
430EnvironmentError__doc__[] = "Base class for I/O related errors.";
431
432
433static PyObject*
434EnvironmentError__init__(PyObject* self, PyObject* args)
435{
436 PyObject* item0 = NULL;
437 PyObject* item1 = NULL;
438 PyObject* item2 = NULL;
439 PyObject* subslice = NULL;
440 PyObject* rtnval = NULL;
441
442 if (!(self = get_self(args)))
443 return NULL;
444
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000445 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000446 return NULL;
447
448 if (PyObject_SetAttrString(self, "args", args) ||
449 PyObject_SetAttrString(self, "errno", Py_None) ||
450 PyObject_SetAttrString(self, "strerror", Py_None) ||
451 PyObject_SetAttrString(self, "filename", Py_None))
452 {
453 goto finally;
454 }
455
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000456 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000457 case 3:
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000458 /* Where a function has a single filename, such as open() or some
459 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
460 * called, giving a third argument which is the filename. But, so
461 * that old code using in-place unpacking doesn't break, e.g.:
Barry Warsaw675ac282000-05-26 19:05:16 +0000462 *
463 * except IOError, (errno, strerror):
464 *
465 * we hack args so that it only contains two items. This also
466 * means we need our own __str__() which prints out the filename
467 * when it was supplied.
468 */
469 item0 = PySequence_GetItem(args, 0);
470 item1 = PySequence_GetItem(args, 1);
471 item2 = PySequence_GetItem(args, 2);
472 if (!item0 || !item1 || !item2)
473 goto finally;
474
475 if (PyObject_SetAttrString(self, "errno", item0) ||
476 PyObject_SetAttrString(self, "strerror", item1) ||
477 PyObject_SetAttrString(self, "filename", item2))
478 {
479 goto finally;
480 }
481
482 subslice = PySequence_GetSlice(args, 0, 2);
483 if (!subslice || PyObject_SetAttrString(self, "args", subslice))
484 goto finally;
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000485 break;
Barry Warsaw675ac282000-05-26 19:05:16 +0000486
487 case 2:
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000488 /* Used when PyErr_SetFromErrno() is called and no filename
489 * argument is given.
490 */
Barry Warsaw675ac282000-05-26 19:05:16 +0000491 item0 = PySequence_GetItem(args, 0);
492 item1 = PySequence_GetItem(args, 1);
493 if (!item0 || !item1)
494 goto finally;
495
496 if (PyObject_SetAttrString(self, "errno", item0) ||
497 PyObject_SetAttrString(self, "strerror", item1))
498 {
499 goto finally;
500 }
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000501 break;
Barry Warsaw675ac282000-05-26 19:05:16 +0000502 }
503
504 Py_INCREF(Py_None);
505 rtnval = Py_None;
506
507 finally:
508 Py_DECREF(args);
509 Py_XDECREF(item0);
510 Py_XDECREF(item1);
511 Py_XDECREF(item2);
512 Py_XDECREF(subslice);
513 return rtnval;
514}
515
516
517static PyObject*
518EnvironmentError__str__(PyObject* self, PyObject* args)
519{
520 PyObject* originalself = self;
521 PyObject* filename;
522 PyObject* serrno;
523 PyObject* strerror;
524 PyObject* rtnval = NULL;
525
526 if (!PyArg_ParseTuple(args, "O", &self))
527 return NULL;
528
529 filename = PyObject_GetAttrString(self, "filename");
530 serrno = PyObject_GetAttrString(self, "errno");
531 strerror = PyObject_GetAttrString(self, "strerror");
532 if (!filename || !serrno || !strerror)
533 goto finally;
534
535 if (filename != Py_None) {
536 PyObject* fmt = PyString_FromString("[Errno %s] %s: %s");
537 PyObject* repr = PyObject_Repr(filename);
538 PyObject* tuple = PyTuple_New(3);
539
540 if (!fmt || !repr || !tuple) {
541 Py_XDECREF(fmt);
542 Py_XDECREF(repr);
543 Py_XDECREF(tuple);
544 goto finally;
545 }
546
547 PyTuple_SET_ITEM(tuple, 0, serrno);
548 PyTuple_SET_ITEM(tuple, 1, strerror);
549 PyTuple_SET_ITEM(tuple, 2, repr);
550
551 rtnval = PyString_Format(fmt, tuple);
552
553 Py_DECREF(fmt);
554 Py_DECREF(tuple);
555 /* already freed because tuple owned only reference */
556 serrno = NULL;
557 strerror = NULL;
558 }
559 else if (PyObject_IsTrue(serrno) && PyObject_IsTrue(strerror)) {
560 PyObject* fmt = PyString_FromString("[Errno %s] %s");
561 PyObject* tuple = PyTuple_New(2);
562
563 if (!fmt || !tuple) {
564 Py_XDECREF(fmt);
565 Py_XDECREF(tuple);
566 goto finally;
567 }
568
569 PyTuple_SET_ITEM(tuple, 0, serrno);
570 PyTuple_SET_ITEM(tuple, 1, strerror);
571
572 rtnval = PyString_Format(fmt, tuple);
573
574 Py_DECREF(fmt);
575 Py_DECREF(tuple);
576 /* already freed because tuple owned only reference */
577 serrno = NULL;
578 strerror = NULL;
579 }
580 else
581 /* The original Python code said:
582 *
583 * return StandardError.__str__(self)
584 *
585 * but there is no StandardError__str__() function; we happen to
586 * know that's just a pass through to Exception__str__().
587 */
588 rtnval = Exception__str__(originalself, args);
589
590 finally:
591 Py_XDECREF(filename);
592 Py_XDECREF(serrno);
593 Py_XDECREF(strerror);
594 return rtnval;
595}
596
597
598static
599PyMethodDef EnvironmentError_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000600 {"__init__", EnvironmentError__init__, METH_VARARGS},
601 {"__str__", EnvironmentError__str__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000602 {NULL, NULL}
603};
604
605
606
607
608static char
609IOError__doc__[] = "I/O operation failed.";
610
611static char
612OSError__doc__[] = "OS system call failed.";
613
614#ifdef MS_WINDOWS
615static char
616WindowsError__doc__[] = "MS-Windows OS system call failed.";
617#endif /* MS_WINDOWS */
618
619static char
620EOFError__doc__[] = "Read beyond end of file.";
621
622static char
623RuntimeError__doc__[] = "Unspecified run-time error.";
624
625static char
626NotImplementedError__doc__[] =
627"Method or function hasn't been implemented yet.";
628
629static char
630NameError__doc__[] = "Name not found globally.";
631
632static char
633UnboundLocalError__doc__[] =
634"Local name referenced but not bound to a value.";
635
636static char
637AttributeError__doc__[] = "Attribute not found.";
638
639
640
641static char
642SyntaxError__doc__[] = "Invalid syntax.";
643
644
645static int
646SyntaxError__classinit__(PyObject* klass)
647{
648 PyObject* emptystring = PyString_FromString("");
649
650 /* Additional class-creation time initializations */
651 if (!emptystring ||
652 PyObject_SetAttrString(klass, "msg", emptystring) ||
653 PyObject_SetAttrString(klass, "filename", Py_None) ||
654 PyObject_SetAttrString(klass, "lineno", Py_None) ||
655 PyObject_SetAttrString(klass, "offset", Py_None) ||
656 PyObject_SetAttrString(klass, "text", Py_None))
657 {
658 Py_XDECREF(emptystring);
659 return -1;
660 }
661 Py_DECREF(emptystring);
662 return 0;
663}
664
665
666static PyObject*
667SyntaxError__init__(PyObject* self, PyObject* args)
668{
669 PyObject* rtnval = NULL;
670 int lenargs;
671
672 if (!(self = get_self(args)))
673 return NULL;
674
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000675 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000676 return NULL;
677
678 if (PyObject_SetAttrString(self, "args", args))
679 goto finally;
680
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000681 lenargs = PySequence_Size(args);
Barry Warsaw675ac282000-05-26 19:05:16 +0000682 if (lenargs >= 1) {
683 PyObject* item0 = PySequence_GetItem(args, 0);
684 int status;
685
686 if (!item0)
687 goto finally;
688 status = PyObject_SetAttrString(self, "msg", item0);
689 Py_DECREF(item0);
690 if (status)
691 goto finally;
692 }
693 if (lenargs == 2) {
694 PyObject* info = PySequence_GetItem(args, 1);
695 PyObject *filename, *lineno, *offset, *text;
696 int status = 1;
697
698 if (!info)
699 goto finally;
700
701 filename = PySequence_GetItem(info, 0);
702 lineno = PySequence_GetItem(info, 1);
703 offset = PySequence_GetItem(info, 2);
704 text = PySequence_GetItem(info, 3);
705
706 Py_DECREF(info);
707
708 if (filename && lineno && offset && text) {
709 status = PyObject_SetAttrString(self, "filename", filename) ||
710 PyObject_SetAttrString(self, "lineno", lineno) ||
711 PyObject_SetAttrString(self, "offset", offset) ||
712 PyObject_SetAttrString(self, "text", text);
713 }
714 Py_XDECREF(filename);
715 Py_XDECREF(lineno);
716 Py_XDECREF(offset);
717 Py_XDECREF(text);
718
719 if (status)
720 goto finally;
721 }
722 Py_INCREF(Py_None);
723 rtnval = Py_None;
724
725 finally:
726 Py_DECREF(args);
727 return rtnval;
728}
729
730
731static PyObject*
732SyntaxError__str__(PyObject* self, PyObject* args)
733{
734 PyObject* msg;
735 PyObject* str;
736
737 if (!PyArg_ParseTuple(args, "O", &self))
738 return NULL;
739
740 if (!(msg = PyObject_GetAttrString(self, "msg")))
741 return NULL;
742
743 str = PyObject_Str(msg);
744 Py_DECREF(msg);
745 return str;
746}
747
748
749PyMethodDef SyntaxError_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000750 {"__init__", SyntaxError__init__, METH_VARARGS},
751 {"__str__", SyntaxError__str__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000752 {NULL, NULL}
753};
754
755
756
757static char
758AssertionError__doc__[] = "Assertion failed.";
759
760static char
761LookupError__doc__[] = "Base class for lookup errors.";
762
763static char
764IndexError__doc__[] = "Sequence index out of range.";
765
766static char
767KeyError__doc__[] = "Mapping key not found.";
768
769static char
770ArithmeticError__doc__[] = "Base class for arithmetic errors.";
771
772static char
773OverflowError__doc__[] = "Result too large to be represented.";
774
775static char
776ZeroDivisionError__doc__[] =
777"Second argument to a division or modulo operation was zero.";
778
779static char
780FloatingPointError__doc__[] = "Floating point operation failed.";
781
782static char
783ValueError__doc__[] = "Inappropriate argument value (of correct type).";
784
785static char
786UnicodeError__doc__[] = "Unicode related error.";
787
788static char
789SystemError__doc__[] = "Internal error in the Python interpreter.\n\
790\n\
791Please report this to the Python maintainer, along with the traceback,\n\
792the Python version, and the hardware/OS platform and version.";
793
794static char
795MemoryError__doc__[] = "Out of memory.";
796
Fred Drake85f36392000-07-11 17:53:00 +0000797static char
798IndentationError__doc__[] = "Improper indentation.";
799
800static char
801TabError__doc__[] = "Improper mixture of spaces and tabs.";
802
Barry Warsaw675ac282000-05-26 19:05:16 +0000803
804
805/* module global functions */
806static PyMethodDef functions[] = {
807 /* Sentinel */
808 {NULL, NULL}
809};
810
811
812
813/* Global C API defined exceptions */
814
815PyObject *PyExc_Exception;
816PyObject *PyExc_StandardError;
817PyObject *PyExc_ArithmeticError;
818PyObject *PyExc_LookupError;
819
820PyObject *PyExc_AssertionError;
821PyObject *PyExc_AttributeError;
822PyObject *PyExc_EOFError;
823PyObject *PyExc_FloatingPointError;
824PyObject *PyExc_EnvironmentError;
825PyObject *PyExc_IOError;
826PyObject *PyExc_OSError;
827PyObject *PyExc_ImportError;
828PyObject *PyExc_IndexError;
829PyObject *PyExc_KeyError;
830PyObject *PyExc_KeyboardInterrupt;
831PyObject *PyExc_MemoryError;
832PyObject *PyExc_NameError;
833PyObject *PyExc_OverflowError;
834PyObject *PyExc_RuntimeError;
835PyObject *PyExc_NotImplementedError;
836PyObject *PyExc_SyntaxError;
Fred Drake85f36392000-07-11 17:53:00 +0000837PyObject *PyExc_IndentationError;
838PyObject *PyExc_TabError;
Barry Warsaw675ac282000-05-26 19:05:16 +0000839PyObject *PyExc_SystemError;
840PyObject *PyExc_SystemExit;
841PyObject *PyExc_UnboundLocalError;
842PyObject *PyExc_UnicodeError;
843PyObject *PyExc_TypeError;
844PyObject *PyExc_ValueError;
845PyObject *PyExc_ZeroDivisionError;
846#ifdef MS_WINDOWS
847PyObject *PyExc_WindowsError;
848#endif
849
850/* Pre-computed MemoryError instance. Best to create this as early as
851 * possibly and not wait until a MemoryError is actually raised!
852 */
853PyObject *PyExc_MemoryErrorInst;
854
855
856
857/* mapping between exception names and their PyObject** */
858static struct
859{
860 char* name;
861 PyObject** exc;
862 PyObject** base; /* NULL == PyExc_StandardError */
863 char* docstr;
864 PyMethodDef* methods;
865 int (*classinit)(PyObject*);
866}
867exctable[] = {
868 /*
869 * The first three classes MUST appear in exactly this order
870 */
871 {"Exception", &PyExc_Exception},
872 {"StandardError", &PyExc_StandardError, &PyExc_Exception,
873 StandardError__doc__},
874 {"TypeError", &PyExc_TypeError, 0, TypeError__doc__},
875 /*
876 * The rest appear in depth-first order of the hierarchy
877 */
878 {"SystemExit", &PyExc_SystemExit, &PyExc_Exception, SystemExit__doc__,
879 SystemExit_methods},
880 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 0, KeyboardInterrupt__doc__},
881 {"ImportError", &PyExc_ImportError, 0, ImportError__doc__},
882 {"EnvironmentError", &PyExc_EnvironmentError, 0, EnvironmentError__doc__,
883 EnvironmentError_methods},
884 {"IOError", &PyExc_IOError, &PyExc_EnvironmentError, IOError__doc__},
885 {"OSError", &PyExc_OSError, &PyExc_EnvironmentError, OSError__doc__},
886#ifdef MS_WINDOWS
887 {"WindowsError", &PyExc_WindowsError, &PyExc_EnvironmentError,
888 WindowsError__doc__},
889#endif /* MS_WINDOWS */
890 {"EOFError", &PyExc_EOFError, 0, EOFError__doc__},
891 {"RuntimeError", &PyExc_RuntimeError, 0, RuntimeError__doc__},
892 {"NotImplementedError", &PyExc_NotImplementedError,
893 &PyExc_RuntimeError, NotImplementedError__doc__},
894 {"NameError", &PyExc_NameError, 0, NameError__doc__},
895 {"UnboundLocalError", &PyExc_UnboundLocalError, &PyExc_NameError,
896 UnboundLocalError__doc__},
897 {"AttributeError", &PyExc_AttributeError, 0, AttributeError__doc__},
898 {"SyntaxError", &PyExc_SyntaxError, 0, SyntaxError__doc__,
899 SyntaxError_methods, SyntaxError__classinit__},
Fred Drake85f36392000-07-11 17:53:00 +0000900 {"IndentationError", &PyExc_IndentationError, &PyExc_SyntaxError,
901 IndentationError__doc__},
902 {"TabError", &PyExc_TabError, &PyExc_IndentationError,
903 TabError__doc__},
Barry Warsaw675ac282000-05-26 19:05:16 +0000904 {"AssertionError", &PyExc_AssertionError, 0, AssertionError__doc__},
905 {"LookupError", &PyExc_LookupError, 0, LookupError__doc__},
906 {"IndexError", &PyExc_IndexError, &PyExc_LookupError,
907 IndexError__doc__},
908 {"KeyError", &PyExc_KeyError, &PyExc_LookupError,
909 KeyError__doc__},
910 {"ArithmeticError", &PyExc_ArithmeticError, 0, ArithmeticError__doc__},
911 {"OverflowError", &PyExc_OverflowError, &PyExc_ArithmeticError,
912 OverflowError__doc__},
913 {"ZeroDivisionError", &PyExc_ZeroDivisionError, &PyExc_ArithmeticError,
914 ZeroDivisionError__doc__},
915 {"FloatingPointError", &PyExc_FloatingPointError, &PyExc_ArithmeticError,
916 FloatingPointError__doc__},
917 {"ValueError", &PyExc_ValueError, 0, ValueError__doc__},
918 {"UnicodeError", &PyExc_UnicodeError, &PyExc_ValueError, UnicodeError__doc__},
919 {"SystemError", &PyExc_SystemError, 0, SystemError__doc__},
920 {"MemoryError", &PyExc_MemoryError, 0, MemoryError__doc__},
921 /* Sentinel */
922 {NULL}
923};
924
925
926
927void
928#ifdef WIN32
929__declspec(dllexport)
930#endif /* WIN32 */
931init_exceptions()
932{
933 char* modulename = "exceptions";
934 int modnamesz = strlen(modulename);
935 int i;
936
937 PyObject* me = Py_InitModule(modulename, functions);
938 PyObject* mydict = PyModule_GetDict(me);
939 PyObject* bltinmod = PyImport_ImportModule("__builtin__");
940 PyObject* bdict = PyModule_GetDict(bltinmod);
941 PyObject* doc = PyString_FromString(module__doc__);
942 PyObject* args;
943
944 PyDict_SetItemString(mydict, "__doc__", doc);
Barry Warsaw8fcaa922000-07-01 04:45:52 +0000945 Py_DECREF(doc);
Barry Warsaw675ac282000-05-26 19:05:16 +0000946 if (PyErr_Occurred())
947 Py_FatalError("exceptions bootstrapping error.");
948
949 /* This is the base class of all exceptions, so make it first. */
950 if (make_Exception(modulename) ||
951 PyDict_SetItemString(mydict, "Exception", PyExc_Exception) ||
952 PyDict_SetItemString(bdict, "Exception", PyExc_Exception))
953 {
954 Py_FatalError("Base class `Exception' could not be created.");
955 }
956
957 /* Now we can programmatically create all the remaining exceptions.
958 * Remember to start the loop at 1 to skip Exceptions.
959 */
960 for (i=1; exctable[i].name; i++) {
961 int status;
962 char* cname = PyMem_NEW(char, modnamesz+strlen(exctable[i].name)+2);
963 PyObject* base;
964
965 (void)strcpy(cname, modulename);
966 (void)strcat(cname, ".");
967 (void)strcat(cname, exctable[i].name);
968
969 if (exctable[i].base == 0)
970 base = PyExc_StandardError;
971 else
972 base = *exctable[i].base;
973
974 status = make_class(exctable[i].exc, base, cname,
975 exctable[i].methods,
976 exctable[i].docstr);
977
978 PyMem_DEL(cname);
979
980 if (status)
981 Py_FatalError("Standard exception classes could not be created.");
982
983 if (exctable[i].classinit) {
984 status = (*exctable[i].classinit)(*exctable[i].exc);
985 if (status)
986 Py_FatalError("An exception class could not be initialized.");
987 }
988
989 /* Now insert the class into both this module and the __builtin__
990 * module.
991 */
992 if (PyDict_SetItemString(mydict, exctable[i].name, *exctable[i].exc) ||
993 PyDict_SetItemString(bdict, exctable[i].name, *exctable[i].exc))
994 {
995 Py_FatalError("Module dictionary insertion problem.");
996 }
997 }
998
999 /* Now we need to pre-allocate a MemoryError instance */
1000 args = Py_BuildValue("()");
1001 if (!args ||
1002 !(PyExc_MemoryErrorInst = PyEval_CallObject(PyExc_MemoryError, args)))
1003 {
1004 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
1005 }
1006 Py_DECREF(args);
1007
1008 /* We're done with __builtin__ */
1009 Py_DECREF(bltinmod);
1010}
1011
1012
1013void
1014#ifdef WIN32
1015__declspec(dllexport)
1016#endif /* WIN32 */
1017fini_exceptions()
1018{
1019 int i;
1020
1021 Py_XDECREF(PyExc_MemoryErrorInst);
1022 PyExc_MemoryErrorInst = NULL;
1023
1024 for (i=0; exctable[i].name; i++) {
1025 Py_XDECREF(*exctable[i].exc);
1026 *exctable[i].exc = NULL;
1027 }
1028}