_jexception.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #*****************************************************************************
  2. # Copyright 2004-2008 Steve Menard
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. #*****************************************************************************
  17. import _jpype
  18. from . import _jclass
  19. _CLASSES = {}
  20. def JException(t):
  21. return t.PYEXC
  22. class JavaException(Exception):
  23. def __init__(self, *data):
  24. if isinstance(data[0], tuple) \
  25. and data[0][0] is _jclass._SPECIAL_CONSTRUCTOR_KEY:
  26. # this is wrapped:
  27. self.__javaobject__ = data[0][1]
  28. self.__javaclass__ = self.__javaobject__.__class__
  29. else:
  30. self.__javaclass__ = _jclass.JClass(self.__class__.JAVACLASSNAME)
  31. self.__javaobject__ = self.__javaclass__(*data)
  32. Exception.__init__(self, self.__javaobject__)
  33. def javaClass(self):
  34. return self.__javaclass__
  35. def message(self):
  36. return self.__javaobject__.getMessage()
  37. def stacktrace(self):
  38. StringWriter = _jclass.JClass("java.io.StringWriter")
  39. PrintWriter = _jclass.JClass("java.io.PrintWriter")
  40. sw = StringWriter()
  41. pw = PrintWriter(sw)
  42. self.__javaobject__.printStackTrace(pw)
  43. pw.flush()
  44. r = sw.toString()
  45. sw.close()
  46. return r
  47. def __str__(self):
  48. return self.__javaobject__.toString()
  49. def _initialize():
  50. _jpype.setJavaExceptionClass(JavaException)
  51. def _makePythonException(name, bc):
  52. if name in _CLASSES:
  53. return _CLASSES[name]
  54. if name == 'java.lang.Throwable':
  55. bases = (JavaException,)
  56. else:
  57. bases = (_makePythonException(bc.getName(), bc.getBaseClass()) ,)
  58. ec = type(name+"PyRaisable", bases, {'JAVACLASSNAME': name})
  59. _CLASSES[name] = ec
  60. return ec