catching exceptions from fortran

Gabriel Genellina gagsl-py2 at
Fri Sep 12 02:23:22 CEST 2008

En Thu, 11 Sep 2008 10:43:08 -0300, john <john.m.roach at> escribió:

> I wrapped some fortran code using F2PY and need to be able to catch
> fortran runtime errors to run the following:
> # "grid" is a wrapped fortran module
> # no runtime errors incurred when run with the correct inputs for
> filetype
> #-------------------------------
> def readGrid( self, coord='xyz' ):
>   mg = ( '.FALSE.', '.TRUE.' )
>   form = ( 'FORMATTED', 'UNFORMATTED' )
>   success = False
>   for m in mg:
>     for f in form:
>       try:
>         if coord == 'xyz':
>           self.grid.readxyz( self.filename, f, m )
>           success = True
>         elif coord == 'xyrb':
>           self.grid.readxyrb( self.filename, f, m )
>           success = True
>         else:
>           import sys
>           print 'gridtype "' + str(coord) + '" not supported. ' \
>               + '<>'
>       except:
>         continue
>   if not success:
>     import sys
>     print 'gridfile "' + str(self.filename) + '" not read in any  
> recognized format' \
>         + ' <>'
> #----------------------------

I suppose you want to stop trying other formats after a successful read;  
in that case put a break statement just below both success=True.
If coord is unrecognized, the code above prints the same message 4 times.  
Instead of printing a message, in those cases usually an exception is  
raised, letting a higher layer handle the error. And using string  
interpolation is a lot easier than building the message in parts:
raise ValueError('gridtype "%s" not supported. <>' %  
If you want to catch errors on the Fortran code *only*, the try/except  
should be more specific (both in scope and what it catches). The Exception  
class is the more generic exception that you should catch.

> basically, what i want to happen is to try to run 'something' with the
> wrapped fortran code and if that doesn't work (error encountered,
> etc.) try something else.  is there an easier way to go about doing
> this?  is there something i'm missing about catching exceptions here?

I'd reorder the code in this way (untested, of course):

def readGrid(self, coord='xyz'):

     def try_all_formats(read_function, filename):
         mg = ('.FALSE.', '.TRUE.')
         form = ('FORMATTED', 'UNFORMATTED')
         success = False
         for m in mg:
             for f in form:
                     read_function(filename, f, m)
                     success = True
                 except Exception, e:
                     # this line only for debugging purposes
                     print "error %r when using m=%r f=%r" % (e, m, f)
         if not success:
             raise ValueError('gridfile "%s" not read '
                    'in any recognized format '
                    '<>' % filename)

     if coord == 'xyz':
         try_all_formats(self.grid.readxyz, self.filename)
     elif coord == 'xyrb':
         try_all_formats(self.grid.readxyrb, self.filename)
         raise ValueError('gridtype "%s" not supported. '
                 '<>' % coord)

I don't know about F2PY but the values ('.FALSE.', '.TRUE.') seem  
suspicious. AFAIR, .FALSE. and .TRUE. are the Fortran spellings of False  
and True in Python - they're not strings, but boolean values. So maybe the  
right way is to use
         mg = (False, True)

Your code above was catching and ignoring everything, even this error, if  
it happened.

Gabriel Genellina

More information about the Python-list mailing list