Search code examples
pythonrexceptionruntime-error

How do I catch an rpy2.rinterface.RRuntimeError in Python?


Setup:

  • Python 3.5.3 |Continuum Analytics, Inc.| (default, Mar 6 2017, 12:15:08)
  • Mac OSX 10.13.1

Problem:

I have downloaded the following R script https://github.com/daleroberts/heston/blob/master/heston.r and I repeatedly call one of the functions in there via Python using the package RPy2. Now, for some of my inputs that I feed into the R function, R returns the following error:

rpy2.rinterface.RRuntimeError: Error in integrate(PIntegrand, lower = 0, upper = Inf, lambda, vbar, eta, : roundoff error was detected

How do I go about catching this RuntimeError in Python?


Solution

  • The RRuntimeError is derived from Exception so you should be able to catch it as you would with any other exception.

    try:
        # your code
    except rpy2.rinterface.RRuntimeError:
        # handle exception
    

    In rpy2 v3.0 and above, RRuntimeError seems to have been moved elsewhere (see example code from documentation) so you may need to use this instead:

    try:
        # your code
    except rpy2.rinterface_lib.embedded.RRuntimeError:
        # handle exception
    

    More on this: https://docs.python.org/3/tutorial/errors.html#handling-exceptions