KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > python > core > exceptions


1 // Copyright 2001 Finn Bock
2

3 package org.python.core;
4
5 import java.lang.reflect.*;
6
7 /**
8  * The builtin exceptions module. The entire module should be imported
9  * from python. None of the methods defined here should be called
10  * from java.
11  */

12
13 public class exceptions implements ClassDictInit {
14
15     public static String JavaDoc __doc__ =
16 "Python's standard exception class hierarchy.\n" +
17 "\n" +
18 "Here is a rundown of the class hierarchy. The classes found here are\n" +
19 "inserted into both the exceptions module and the `built-in' module. "+
20 "It is\n" +
21 "recommended that user defined class based exceptions be derived from the\n" +
22 "`Exception' class, although this is currently not enforced.\n" +
23 "\n" +
24 "Exception\n" +
25 " |\n" +
26 " +-- SystemExit\n" +
27 " +-- StopIteration\n" +
28 " +-- StandardError\n" +
29 " | |\n" +
30 " | +-- KeyboardInterrupt\n" +
31 " | +-- ImportError\n" +
32 " | +-- EnvironmentError\n" +
33 " | | |\n" +
34 " | | +-- IOError\n" +
35 " | | +-- OSError\n" +
36 " | | |\n" +
37 " | | +-- WindowsError\n" +
38 " | |\n" +
39 " | +-- EOFError\n" +
40 " | +-- RuntimeError\n" +
41 " | | |\n" +
42 " | | +-- NotImplementedError\n" +
43 " | |\n" +
44 " | +-- NameError\n" +
45 " | | |\n" +
46 " | | +-- UnboundLocalError\n" +
47 " | |\n" +
48 " | +-- AttributeError\n" +
49 " | +-- SyntaxError\n" +
50 " | | |\n" +
51 " | | +-- IndentationError\n" +
52 " | | |\n" +
53 " | | +-- TabError\n" +
54 " | |\n" +
55 " | +-- TypeError\n" +
56 " | +-- AssertionError\n" +
57 " | +-- LookupError\n" +
58 " | | |\n" +
59 " | | +-- IndexError\n" +
60 " | | +-- KeyError\n" +
61 " | |\n" +
62 " | +-- ArithmeticError\n" +
63 " | | |\n" +
64 " | | +-- OverflowError\n" +
65 " | | +-- ZeroDivisionError\n" +
66 " | | +-- FloatingPointError\n" +
67 " | |\n" +
68 " | +-- ValueError\n" +
69 " | | |\n" +
70 " | | +-- UnicodeError\n" +
71 " | |\n" +
72 " | +-- ReferenceError\n" +
73 " | +-- SystemError\n" +
74 " | +-- MemoryError\n" +
75 " |\n" +
76 " +---Warning\n" +
77 " |\n" +
78 " +-- UserWarning\n" +
79 " +-- DeprecationWarning\n" +
80 " +-- SyntaxWarning\n" +
81 " +-- OverflowWarning\n" +
82 " +-- RuntimeWarning";
83
84     private exceptions() { ; }
85
86     /** <i>Internal use only. Do not call this method explicit.</i> */
87     public static void classDictInit(PyObject dict) {
88         dict.invoke("clear");
89         dict.__setitem__("__name__", new PyString("exceptions"));
90         dict.__setitem__("__doc__", new PyString(__doc__));
91
92         ThreadState ts = Py.getThreadState();
93         if (ts.systemState == null) {
94             ts.systemState = Py.defaultSystemState;
95         }
96         // Push frame
97
PyFrame frame = new PyFrame(null, new PyStringMap());
98         frame.f_back = ts.frame;
99         if (frame.f_builtins == null) {
100             if (frame.f_back != null) {
101                 frame.f_builtins = frame.f_back.f_builtins;
102             } else {
103                 frame.f_builtins = ts.systemState.builtins;
104             }
105         }
106         ts.frame = frame;
107
108
109         buildClass(dict, "Exception", null, "Exception",
110                    "Proposed base class for all exceptions.");
111
112         buildClass(dict, "StandardError", "Exception", "empty__init__",
113                    "Base class for all standard Python exceptions.");
114
115         buildClass(dict, "SyntaxError", "StandardError", "SyntaxError",
116                    "Invalid syntax");
117
118         buildClass(dict, "IndentationError", "SyntaxError", "empty__init__",
119                    "Improper indentation");
120
121         buildClass(dict, "TabError", "IndentationError", "empty__init__",
122                    "Improper mixture of spaces and tabs.");
123
124         buildClass(dict, "EnvironmentError", "StandardError",
125                    "EnvironmentError",
126                    "Base class for I/O related errors.");
127
128         buildClass(dict, "IOError", "EnvironmentError", "empty__init__",
129                    "I/O operation failed.");
130
131         buildClass(dict, "OSError", "EnvironmentError", "empty__init__",
132                    "OS system call failed.");
133
134         buildClass(dict, "RuntimeError", "StandardError", "empty__init__",
135                    "Unspecified run-time error.");
136
137         buildClass(dict, "NotImplementedError", "RuntimeError",
138                    "empty__init__",
139                    "Method or function hasn't been implemented yet.");
140
141         buildClass(dict, "SystemError", "StandardError", "empty__init__",
142                    "Internal error in the Python interpreter.\n\n" +
143                    "Please report this to the Python maintainer, "+
144                    "along with the traceback,\n" +
145                    "the Python version, and the hardware/OS "+
146                    "platform and version.");
147
148         buildClass(dict, "ReferenceError", "StandardError", "empty__init__",
149                     "Weak ref proxy used after referent went away.");
150
151         buildClass(dict, "EOFError", "StandardError", "empty__init__",
152                    "Read beyond end of file.");
153
154         buildClass(dict, "ImportError", "StandardError", "empty__init__",
155                    "Import can't find module, or can't find name in module.");
156
157         buildClass(dict, "TypeError", "StandardError", "empty__init__",
158                    "Inappropriate argument type.");
159
160         buildClass(dict, "ValueError", "StandardError", "empty__init__",
161                    "Inappropriate argument value (of correct type).");
162
163         buildClass(dict, "UnicodeError", "ValueError", "empty__init__",
164                    "Unicode related error.");
165
166         buildClass(dict, "KeyboardInterrupt", "StandardError",
167                    "empty__init__",
168                    "Program interrupted by user.");
169
170         buildClass(dict, "AssertionError", "StandardError", "empty__init__",
171                    "Assertion failed.");
172
173         buildClass(dict, "ArithmeticError", "StandardError", "empty__init__",
174                    "Base class for arithmetic errors.");
175
176         buildClass(dict, "OverflowError", "ArithmeticError", "empty__init__",
177                    "Result too large to be represented.");
178
179         buildClass(dict, "FloatingPointError", "ArithmeticError",
180                    "empty__init__",
181                    "Floating point operation failed.");
182
183         buildClass(dict, "ZeroDivisionError", "ArithmeticError",
184                    "empty__init__",
185                    "Second argument to a division or modulo operation "+
186                    "was zero.");
187
188         buildClass(dict, "LookupError", "StandardError", "empty__init__",
189                    "Base class for lookup errors.");
190
191         buildClass(dict, "IndexError", "LookupError", "empty__init__",
192                    "Sequence index out of range.");
193
194         buildClass(dict, "KeyError", "LookupError", "empty__init__",
195                    "Mapping key not found.");
196
197         buildClass(dict, "AttributeError", "StandardError", "empty__init__",
198                    "Attribute not found.");
199
200         buildClass(dict, "NameError", "StandardError", "empty__init__",
201                    "Name not found globally.");
202
203         buildClass(dict, "UnboundLocalError", "NameError", "empty__init__",
204                    "Local name referenced but not bound to a value.");
205
206         buildClass(dict, "MemoryError", "StandardError", "empty__init__",
207                    "Out of memory.");
208
209         buildClass(dict, "SystemExit", "Exception", "SystemExit",
210                    "Request to exit from the interpreter.");
211
212         buildClass(dict, "StopIteration", "Exception", "empty__init__",
213                    "Signal the end from iterator.next().");
214
215         buildClass(dict, "Warning", "Exception", "empty__init__",
216                    "Base class for warning categories.");
217
218         buildClass(dict, "UserWarning", "Warning", "empty__init__",
219                    "Base class for warnings generated by user code.");
220
221         buildClass(dict, "DeprecationWarning", "Warning", "empty__init__",
222                    "Base class for warnings about deprecated features.");
223
224         buildClass(dict, "SyntaxWarning", "Warning", "empty__init__",
225                    "Base class for warnings about dubious syntax.");
226
227         buildClass(dict, "RuntimeWarning", "Warning", "empty__init__",
228                    "Base class for warnings about dubious runtime behavior.");
229
230         buildClass(dict, "OverflowWarning", "Warning", "empty__init__",
231                    "Base class for warnings about numeric overflow.");
232
233         ts.frame = ts.frame.f_back;
234     }
235
236
237     // An empty __init__ method
238
public static PyObject empty__init__(PyObject[] arg, String JavaDoc[] kws) {
239         PyObject dict = new PyStringMap();
240         dict.__setitem__("__module__", new PyString("exceptions"));
241         return dict;
242     }
243
244
245     public static PyObject Exception(PyObject[] arg, String JavaDoc[] kws) {
246         PyObject dict = empty__init__(arg, kws);
247         dict.__setitem__("__init__", getJavaFunc("Exception__init__"));
248         dict.__setitem__("__str__", getJavaFunc("Exception__str__"));
249         dict.__setitem__("__getitem__", getJavaFunc("Exception__getitem__"));
250         return dict;
251     }
252
253     public static void Exception__init__(PyObject[] arg, String JavaDoc[] kws) {
254         ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args");
255         PyObject self = ap.getPyObject(0);
256         PyObject args = ap.getList(1);
257
258         self.__setattr__("args", args);
259     }
260
261     public static PyString Exception__str__(PyObject[] arg, String JavaDoc[] kws) {
262         ArgParser ap = new ArgParser("__str__", arg, kws, "self");
263         PyObject self = ap.getPyObject(0);
264
265         PyObject args = self.__getattr__("args");
266         if (!args.__nonzero__())
267             return new PyString("");
268         else if (args.__len__() == 1)
269             return args.__getitem__(0).__str__();
270         else
271             return args.__str__();
272     }
273
274     public static PyObject Exception__getitem__(PyObject[] arg,
275                                                 String JavaDoc[] kws)
276     {
277         ArgParser ap = new ArgParser("__getitem__", arg, kws, "self", "i");
278         PyObject self = ap.getPyObject(0);
279         PyObject i = ap.getPyObject(1);
280
281         return self.__getattr__("args").__getitem__(i);
282     }
283
284
285     public static PyObject SyntaxError(PyObject[] arg, String JavaDoc[] kws) {
286         PyObject __dict__ = empty__init__(arg, kws);
287         __dict__.__setitem__("filename", Py.None);
288         __dict__.__setitem__("lineno", Py.None);
289         __dict__.__setitem__("offset", Py.None);
290         __dict__.__setitem__("text", Py.None);
291         __dict__.__setitem__("msg", new PyString(""));
292
293         __dict__.__setitem__("__init__", getJavaFunc("SyntaxError__init__"));
294         __dict__.__setitem__("__str__", getJavaFunc("SyntaxError__str__"));
295         return __dict__;
296     }
297
298     public static void SyntaxError__init__(PyObject[] arg, String JavaDoc[] kws) {
299         ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args");
300         PyObject self = ap.getPyObject(0);
301         PyObject args = ap.getList(1);
302
303         self.__setattr__("args", args);
304         if (args.__len__() >= 1)
305             self.__setattr__("msg", args.__getitem__(0));
306         if (args.__len__() == 2) {
307             PyObject info = args.__getitem__(1);
308             try {
309                 PyObject[] tmp = Py.unpackSequence(info, 4);
310                 self.__setattr__("filename", tmp[0]);
311                 self.__setattr__("lineno", tmp[1]);
312                 self.__setattr__("offset", tmp[2]);
313                 self.__setattr__("text", tmp[3]);
314             } catch (PyException exc) { ; }
315         }
316     }
317
318     public static PyString SyntaxError__str__(PyObject[] arg, String JavaDoc[] kws) {
319         ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args");
320         PyObject self = ap.getPyObject(0);
321         PyString str = self.__getattr__("msg").__str__();
322         PyObject filename = basename(self.__findattr__("filename"));
323         PyObject lineno = self.__findattr__("lineno");
324         if (filename instanceof PyString && lineno instanceof PyInteger)
325             return new PyString(str + " (" + filename + ", line " +
326                                 lineno + ")");
327         else if (filename instanceof PyString)
328             return new PyString(str + " (" + filename + ")");
329         else if (lineno instanceof PyInteger)
330             return new PyString(str + " (line " + lineno + ")");
331         return str;
332     }
333
334     private static PyObject basename(PyObject filename) {
335         if (filename instanceof PyString) {
336              int i = ((PyString) filename).rfind(java.io.File.separator);
337              if (i >= 0)
338                   return filename.__getslice__(
339                        new PyInteger(i+1), new PyInteger(Integer.MAX_VALUE));
340         }
341         return filename;
342     }
343
344     public static PyObject EnvironmentError(PyObject[] arg, String JavaDoc[] kws) {
345         PyObject dict = empty__init__(arg, kws);
346         dict.__setitem__("__init__", getJavaFunc("EnvironmentError__init__"));
347         dict.__setitem__("__str__", getJavaFunc("EnvironmentError__str__"));
348         return dict;
349     }
350
351     public static void EnvironmentError__init__(PyObject[] arg,
352                                                 String JavaDoc[] kws)
353     {
354         ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args");
355         PyObject self = ap.getPyObject(0);
356         PyObject args = ap.getList(1);
357
358         self.__setattr__("args", args);
359         self.__setattr__("errno", Py.None);
360         self.__setattr__("strerror", Py.None);
361         self.__setattr__("filename", Py.None);
362         if (args.__len__() == 3) {
363             // open() errors give third argument which is the filename. BUT,
364
// so common in-place unpacking doesn't break, e.g.:
365
//
366
// except IOError, (errno, strerror):
367
//
368
// we hack args so that it only contains two items. This also
369
// means we need our own __str__() which prints out the filename
370
// when it was supplied.
371
PyObject[] tmp = Py.unpackSequence(args, 3);
372             self.__setattr__("errno", tmp[0]);
373             self.__setattr__("strerror", tmp[1]);
374             self.__setattr__("filename", tmp[2]);
375             self.__setattr__("args",
376                      args.__getslice__(Py.Zero, Py.newInteger(2), Py.One));
377         }
378         if (args.__len__() == 2) {
379             // common case: PyErr_SetFromErrno()
380
PyObject[] tmp = Py.unpackSequence(args, 2);
381             self.__setattr__("errno", tmp[0]);
382             self.__setattr__("strerror", tmp[1]);
383         }
384     }
385
386     public static PyString EnvironmentError__str__(PyObject[] arg,
387                                                    String JavaDoc[] kws)
388     {
389         ArgParser ap = new ArgParser("__init__", arg, kws, "self");
390         PyObject self = ap.getPyObject(0);
391
392         if (self.__getattr__("filename") != Py.None) {
393             return Py.newString("[Errno %s] %s: %s").__mod__(
394                        new PyTuple(new PyObject[] {
395                             self.__getattr__("errno"),
396                             self.__getattr__("strerror"),
397                             self.__getattr__("filename")})).__str__();
398         } else if (self.__getattr__("errno").__nonzero__() &&
399                    self.__getattr__("strerror").__nonzero__()) {
400             return Py.newString("[Errno %s] %s").__mod__(
401                        new PyTuple(new PyObject[] {
402                            self.__getattr__("errno"),
403                            self.__getattr__("strerror")})).__str__();
404         } else {
405              return Exception__str__(arg, kws);
406         }
407     }
408
409
410
411     public static PyObject SystemExit(PyObject[] arg, String JavaDoc[] kws) {
412         PyObject dict = empty__init__(arg, kws);
413         dict.__setitem__("__init__", getJavaFunc("SystemExit__init__"));
414         return dict;
415     }
416
417     public static void SystemExit__init__(PyObject[] arg, String JavaDoc[] kws) {
418         ArgParser ap = new ArgParser("__init__", arg, kws, "self", "args");
419         PyObject self = ap.getPyObject(0);
420         PyObject args = ap.getList(1);
421
422         self.__setattr__("args", args);
423         if (args.__len__() == 0)
424             self.__setattr__("code", Py.None);
425         else if (args.__len__() == 1)
426             self.__setattr__("code", args.__getitem__(0));
427         else
428             self.__setattr__("code", args);
429     }
430
431
432     private static PyObject getJavaFunc(String JavaDoc name) {
433         return Py.newJavaFunc(exceptions.class, name);
434     }
435
436     private static PyObject buildClass(PyObject dict, String JavaDoc classname,
437                                        String JavaDoc superclass,
438                                        String JavaDoc classCodeName,
439                                        String JavaDoc doc) {
440         PyObject[] sclass = Py.EmptyObjects;
441         if (superclass != null)
442              sclass = new PyObject[] {
443                             dict.__getitem__(new PyString(superclass)) };
444         PyObject cls = Py.makeClass(
445                             classname, sclass,
446                             Py.newJavaCode(exceptions.class, classCodeName),
447                             new PyString(doc));
448         dict.__setitem__(classname, cls);
449         return cls;
450     }
451 }
452
453
Popular Tags