From: Updike, C. <Cla...@jh...> - 2006-05-31 17:28:44
|
I have used the following static helper method. It's based on=20 Py.formatException (but a bit simpler), and is designed to work=20 with exceptions thrown from an interpreter instance regardless=20 of whether the underlying exception is python or java (if I=20 recall correctly). Good luck, Clark /** * Returns the exception message, akin to java exception's getMessage() * method (not supported properly in Jython). * @param pye a python exception instance=20 * @return a string containing the python exception's message */ public static String getExceptionMessage(PyException pye) { // derivative of Jython's Py.formatException() method StringBuffer buf =3D new StringBuffer(128); if (pye.type instanceof PyClass) { buf.append(((PyClass) pye.type).__name__); } else { buf.append(pye.type.__str__()); } if (pye.value !=3D Py.None) { buf.append(": "); if (__builtin__.isinstance(pye.value, (PyClass) Py.SyntaxError)) { buf.append(pye.value.__getitem__(0).__str__()); } else { buf.append(pye.value.__str__()); } } return buf.toString(); } =20 > -----Original Message----- > From: jyt...@li...=20 > [mailto:jyt...@li...] On Behalf=20 > Of Kent Johnson > Sent: Wednesday, May 31, 2006 12:33 PM > To: jyt...@li... > Subject: [Jython-users] Getting PyException details from Java >=20 > Hi, >=20 > When I catch a Jython exception from Java code, is there a=20 > clean way to retrieve the message from the exception? I am=20 > using this ugly bit: >=20 > catch (PyException e) { > String msg =3D=20 > ((PyTuple)e.value.__getattr__("args")).list[0].toString(); > ...etc > } >=20 > Dissecting the above: > e.value is the actual Jython exception instance wrapped by=20 > the PyException. It is a PyObject so I use __getattr__ to=20 > retrieve the args.=20 > args is a PyTuple and must be cast as such before retrieving=20 > the actual list data. >=20 > Thanks, > Kent |