Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching Ironpython Exception in C#

I'm embedding IronPython 2.0 in C#. In IronPython, I defined my own exception with:

def foobarException(Exception):
    pass 

and raise it somewhere with:

raise foobarException( "This is the Exception Message" )

Now in C#, I have:

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"
}
like image 457
foobar Avatar asked Mar 05 '09 11:03

foobar


People also ask

What is the use of IronPython?

IronPython works as an extension to the . NET Framework, but it can also be used by . NET projects to take advantage of Python's scripting power. Other than that, since IronPython is a real implementation of Python itself, there's no need to learn a new language or extra features if you already know Python.

Is try catch Pythonic?

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.

What is catch exception in C#?

catch – When an exception occurs, the Catch block of code is executed. This is where you are able to handle the exception, log it, or ignore it. finally – The finally block allows you to execute certain code if an exception is thrown or not. For example, disposing of an object that must be disposed of.

Are exceptions Pythonic?

An exception is a Python object that represents an error. When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.


1 Answers

When you catch an IronPython exception from C#, you can use the Python engine to format the traceback:

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

You can pull the exception name out of the traceback. Otherwise, you will have to call into the IronPython hosting API to retrieve information directly from the exception instance. engine.Operations has useful methods for these kinds of interactions.

like image 131
fuzzyman Avatar answered Sep 24 '22 02:09

fuzzyman