2009-03-05 51 views
6

我在C#中嵌入IronPython 2.0。在IronPython的,我定義我自己的異常,並:在C#中捕捉Ironpython異常#

def foobarException(Exception): 
    pass 

某處有提高吧:在C#

raise foobarException("This is the Exception Message") 

現在,我有:

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" 
} 
+0

你試過用調試器嗎?您應該看到異常類型或內部異常,或者存儲實際python異常的地方。 – OregonGhost 2009-03-05 12:33:27

+0

是的,我試着用調試器,但找不到它。 事情是它與IronPython 1.1一起工作。當我在e.Data [「PythonExceptionInfo」]中正確記得時,實際上有python exception.message。在e.Message中有Exception的名字。 – foobar 2009-03-05 14:51:52

回答

1

我最後的解決辦法是:

我有傳遞給我的IronPython的代碼在C#中的結果類。在Ironpython中,我用我所有的計算值填充結果類。對於這個類,我只是添加了一個成員變量IronPythonExceptionName。現在,我只是在IronPython上進行一個簡單的嘗試:

try: 
    complicatedIronPythonFunction() 
except Exception, inst: 
    result.IronPythonExceptionName = inst.__class__.__name__ 
    raise inst 
0

假設你編譯你的python代碼與.NET等價的編譯器,你將有一個靜態類型,這只是一個例外。如果這個異常是公開的(導出類型),那麼你在你的項目中引用包含你的python代碼的程序集,並在一些python命名空間中挖掘foobarException類型。這樣C#將能夠匹配該異常。這是您可以正確執行此操作的唯一方法。

3

IronPython將.NET異常映射到Python異常的方式並不總是直截了當;很多異常報告爲SystemError(但如果您導入.NET異常類型,則可以在except子句中指定)。您可以使用

type(e).__name__ 

獲得Python類型的異常如果你想在.NET異常類型,請確保您有import clr的模塊中。它使.NET屬性在對象上可用,例如字符串上的ToUpper()方法。

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' 
15

當你然後你就可以使用.clsException屬性訪問的.NET異常捕捉來自C#的IronPython異常,您可以使用Python引擎格式化回溯:

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

您可以將異常名稱從回溯中拉出。否則,您將不得不調用IronPython託管API來直接從異常實例中檢索信息。 engine.Operations爲這些交互提供了有用的方法。