質問

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"
}
役に立ちましたか?

解決 3

最終的な解決策は次のとおりです。

Ironpythonコードに渡されるC#の結果クラスがあります。 Ironpythonでは、計算されたすべての値で結果クラスを埋めます。このクラスに、メンバー変数IronPythonExceptionNameを追加しました。これで、IronPythonで簡単に試すことができます。

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

他のヒント

C#からIronPython例外をキャッチすると、Pythonエンジンを使用してトレースバックをフォーマットできます。

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

トレースバックから例外名を引き出すことができます。それ以外の場合は、IronPythonホスティングAPIを呼び出して、例外インスタンスから直接情報を取得する必要があります。 engine.Operations には、この種の相互作用に役立つメソッドがあります。

IronPythonが.NET例外をPython例外にマップする方法は、必ずしも簡単ではありません。多くの例外は SystemError として報告されます(ただし、.NET例外タイプをインポートする場合は、 except 句で指定できます)。を使用して、例外のPythonタイプを取得できます

type(e).__name__

.NET例外タイプが必要な場合は、モジュールに import clr があることを確認してください。文字列の ToUpper()メソッドのように、オブジェクトで.NET属性を使用できるようにします。次に、 .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'

Pythonコードを.NETの同等のコンパイラでコンパイルしたと仮定すると、その例外である静的な型になります。この例外がパブリック(エクスポートされた型)の場合、プロジェクトでpythonコードを含むアセンブリを参照し、Python名前空間でfoobarException型を掘り下げます。そうすれば、C#はその例外に一致するように入力できます。これが適切にそれを行うことができる唯一の方法です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top