Skip to content

Exception chaining/cause not mirrored into Python #1047

@pelson

Description

@pelson

Both Python and Java have exception chaining (Throwable.getCause() in Java, exception.__cause__ in Python).

This information doesn't make it across from Java to Python though. Take the following snippet:

import jpype as jp
jp.startJVM()


java = jp.JPackage('java')
e1 = java.lang.RuntimeException("Some parent exception")
e2 = java.lang.RuntimeException("Some message", e1)

When we inspect the object:

>>> print(e2.__cause__, e2.__context__)
None None

>>> raise e2
Traceback (most recent call last):
  File "/home/pelson/github/jpype/jpype/support/exception_cause.py", line 19, in <module>
    raise e2
java.lang.RuntimeException: java.lang.RuntimeException: Some message

By adding the exception to __cause__ (via e2.__cause__ = e1) we get an improved exception:

java.lang.RuntimeException: java.lang.RuntimeException: Some parent exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/pelson/github/jpype/jpype/support/exception_cause.py", line 19, in <module>
    raise e2
java.lang.RuntimeException: java.lang.RuntimeException: Some message

In investigating this, I also wondered if I could pass a Python exception as a cause for a Throwable, but unfortunately that wasn't possible:

>>> e1 = ValueError('foo')
>>> e2 = java.lang.RuntimeException("Some message", e1)

TypeError: No matching overloads found for constructor java.lang.RuntimeException(str,ValueError), options are:
	public java.lang.RuntimeException()
	public java.lang.RuntimeException(java.lang.String)
	public java.lang.RuntimeException(java.lang.String,java.lang.Throwable)
	public java.lang.RuntimeException(java.lang.Throwable)

I'm not sure on the practicalities, but it would be also interesting if we could make BaseException be understood as a Throwable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementImprovement in capability planned for future release

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions