在不丢失类型信息的情况下在 IronPython 中捕获 C# 异常
Catching C# exceptions in IronPython without losing type information
在我的 IronPython 脚本中,我调用了各种 C# 方法,这些方法可能会引发各种类型的异常。
使用此 C# 代码:
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");
}
}
这个 IronPython 代码:
try:
Test().foo()
except Exception as exc:
print(repr(exc))
只会打印 Exception("foo")
。如何确定异常是 FooException
还是 BarException
?
我设法弄明白了。
IronPython 异常对象有一个 clsException
成员,其中包含原始 C# 异常对象。
try:
Test().foo()
except Exception as exc:
print(isinstance(exc.clsException, FooException))
在我的 IronPython 脚本中,我调用了各种 C# 方法,这些方法可能会引发各种类型的异常。
使用此 C# 代码:
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");
}
}
这个 IronPython 代码:
try:
Test().foo()
except Exception as exc:
print(repr(exc))
只会打印 Exception("foo")
。如何确定异常是 FooException
还是 BarException
?
我设法弄明白了。
IronPython 异常对象有一个 clsException
成员,其中包含原始 C# 异常对象。
try:
Test().foo()
except Exception as exc:
print(isinstance(exc.clsException, FooException))