mic_e
mic_e

Reputation: 5840

Catching C# exceptions in IronPython without losing type information

From my IronPython script, I call various C# methods, which may throw various types of exceptions.

With this C# code:

public class FooException : Exception {}
public class BarException : Exception {}

public class Test {
    public void foo() {
        throw new FooException("foo");
    }
    public void bar() {
        throw new BarException("bar");
    }
}

This IronPython code:

try:
    Test().foo()
except Exception as exc:
    print(repr(exc))

Will just print Exception("foo"). How do I determine whether the exception was a FooException or a BarException?

Upvotes: 2

Views: 373

Answers (1)

mic_e
mic_e

Reputation: 5840

I managed to figure it out. The IronPython exception object has a clsException member which contains the original C# exception object.

try:
    Test().foo()
except Exception as exc:
    print(isinstance(exc.clsException, FooException))

Upvotes: 1

Related Questions