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"
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With