2

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?

eugenhu
  • 1,168
  • 13
  • 22
Ben
  • 465
  • 2
  • 6
  • 17

3 Answers3

9

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

eugenhu
  • 1,168
  • 13
  • 22
  • It may be under this path `rpy2.rinterface.embedded.RRuntimeError` – wassname Jun 10 '19 at 05:21
  • @wassname Yeah you're probably right, I might just remove references to the source code since it's always eventually going to be outdated. – eugenhu Jun 11 '19 at 05:05
2

Python makes catching exceptions relatively easy.

try:
    # some code
except Exception, e:
    # Log the exception.
collector
  • 940
  • 1
  • 8
  • 14
  • A RuntimeError is an exception in Python. https://docs.python.org/2/library/exceptions.html#exceptions.RuntimeError – collector Nov 15 '17 at 12:21
0

I could not get the rpy2.rinterface.RRuntimeError to work, but the workaround below worked for me.

Installing tryCatchLog:

%%R
install.packages('tryCatchLog')
library('tryCatchLog')

If using it in a function:

def test_R_error_handling():
  %R tryCatchLog( expr = result <- 'a'+2, finally = result <- -1 )
  result = ro.globalenv['result'][0]
  if result == -1:
    print(result)
    return
  else:
    print('\nFunction continued')
    return True

This is on my post on rpy2 error handling. I hope this helps anyone experiencing the same issues.

RianLauw
  • 85
  • 7