[IronPython] Checking for Python exception in C#

Dino Viehland dinov at microsoft.com
Tue Jun 8 21:16:50 CEST 2010


You can just use a normal try/catch.  IronPython has a mapping between .NET exceptions and Python exceptions.  We actually have documentation on this over here http://ironpython.codeplex.com/wikipage?title=Exception%20Model.  But apparently it's out of date for StopIteration.  For that we now define our own StopIterationException in IronPython.Runtime.Exceptions which you can catch.

For 2.7 we've added support for light exceptions - so if you're downloading the source from CodePlex you'll see some methods are decorated with a [LightThrowing] attribute.  Those methods will return a value which is actual a wrapped exception.  For those you can use the LightExceptions class to see if the return value is a light exception and the code will look more like what you have below.

From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of Tristan Zajonc
Sent: Tuesday, June 08, 2010 10:26 AM
To: Discussion of IronPython
Subject: [IronPython] Checking for Python exception in C#

Hi,

I'm trying to get my head around the IronPython API by implementing a simple work-around for what I believe is a bug in the next() builtin,which I reported here: http://ironpython.codeplex.com/workitem/27383.  This is my first look inside IronPython so this question, I assume, is pretty basic. How can I handle Python exceptions returned by TryInvokeUnaryOperator?  I'm currently trying to do this to implement the default value argument in the next builtin.

        public static object next(CodeContext/*!*/ context, object o) {
            object value;
            if (PythonTypeOps.TryInvokeUnaryOperator(context, o, "next", out value)) {
                return value;
            }
            throw PythonOps.TypeError("{0} object is not an iterator.", PythonTypeOps.GetName(o));
        }

        public static object next(CodeContext/*!*/ context, object o, object defaultVal) {
            object value = next(context, o);
            // This doesn't work.
            if (value is StopIterationException) {
                return defaultVal;
            }
            return value;
        }

Thanks,
Tristan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20100608/1c42845a/attachment.html>


More information about the Ironpython-users mailing list