6

我在 C# 中嵌入 IronPython 2.0。在 IronPython 中,我定义了自己的异常:

def foobarException(Exception):
    pass 

并在某处提出:

raise foobarException( "This is the Exception Message" )

现在在 C# 中,我有:

try
{
   callIronPython();
}
catch (Exception e)
{
   // How can I determine the name (foobarException) of the Exception
   // that is thrown from IronPython?   
   // With e.Message, I get "This is the Exception Message"
}
4

4 回答 4

16

当您从 C# 捕获 IronPython 异常时,您可以使用 Python 引擎来格式化回溯:

catch (Exception e)
{
    ExceptionOperations eo = _engine.GetService<ExceptionOperations>(); 
    string error = eo.FormatException(e); 
    Console.WriteLine(error);
}

您可以从回溯中提取异常名称。否则,您将不得不调用 IronPython 托管 API 以直接从异常实例中检索信息。engine.Operations对这些类型的交互有有用的方法。

于 2009-03-08T18:39:15.613 回答
3

IronPython 将 .NET 异常映射到 Python 异常的方式并不总是那么简单。许多异常被报告为SystemError(尽管如果您导入 .NET 异常类型,您可以在except子句中指定它)。您可以使用获取异常的 Python 类型

type(e).__name__

如果您想要 .NET 异常类型,请确保您import clr在模块中有。它使 .NET 属性在对象上可用,就像ToUpper()字符串上的方法一样。然后您可以使用以下.clsException属性访问 .NET 异常:

import clr
try:
    1/0
except Exception, e:
    print type(e).__name__
    print type(e.clsException).__name__

印刷:

ZeroDivisionError      # the python exception
DivideByZeroException  # the corresponding .NET exception

捕获您想要的特定 .NET 异常的示例:

from System import DivideByZeroException
try:
    1/0
except DivideByZeroException:
    print 'caught'
于 2009-03-05T15:06:34.420 回答
1

我的最终解决方案是:

我在 C# 中有一个结果类,它传递给我的 Ironpython 代码。在 Ironpython 中,我用我所有的计算值填充结果类。我刚刚向这个类添加了一个成员变量 IronPythonExceptionName。现在我在 IronPython 中做了一个简单的尝试:

try: 
    complicatedIronPythonFunction()
except Exception, inst:
    result.IronPythonExceptionName = inst.__class__.__name__
    raise inst
于 2009-04-21T11:32:11.153 回答
0

假设您使用 .NET 等效编译器编译了您的 python 代码,您将有一个静态类型,它就是那个异常。如果此异常是公共的(导出类型),那么您在项目中引用包含您的 python 代码的程序集并在某些 python 命名空间中挖掘类型 foobarException。这样 C# 将能够键入匹配该异常。这是您可以正确执行此操作的唯一方法。

于 2009-03-05T11:39:55.710 回答