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: [email protected] 
[mailto:[email protected]] 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
_______________________________________________
Users mailing list
[email protected]
http://lists.ironpython.com/listinfo.cgi/users-ironpython.com

Reply via email to