2

I'm using rpy2 in Google Colab to make use of an R library within a long Python function. I need to catch any R Runtime errors to prevent my function from executing the remaining code.

Running the below:

try:
  %R 'a' + 2
except Exception as ex:
  print('\nR error occurred:', ex)

Has no effect and prints in Colab:

R[write to console]: Error in "a" + 2 : non-numeric argument to binary operator

Error in "a" + 2 : non-numeric argument to binary operator

This post recommends using one of the below as the exception:

  • rpy2.rinterface.RRuntimeError
  • rpy2.rinterface_lib.embedded.RRuntimeError
  • rpy2.rinterface.embedded.RRuntimeError

But none of them works. I suspect it's not raising it as a runtime error.

The best alternative so far is using tryCatchLog() within R and handling the response in an if statement (since it's inside a function):

def test_R_error_handling():
  %R result <- 100
  # Must put tryCatch() function in one line for R magic to work.
  # Use pipe operator (ie. |) to split lines that has to be split
  %R result <- tryCatch(expr = 'a'+2, error = function(e) { message(paste('TryCatch Error: ', e)) | return(-1) }, finally = message('TryCatch complete'))
  result = ro.globalenv['result'][0]
  if result.any() == -1:
    print('Ended abruptly:', result)
    return
  else:
    print('\nFunction continued, final result:', result)
    return True

But I think there are better ways of doing this. I would appreciate any advice!

RianLauw
  • 85
  • 7
  • I'm making edits as I discover better ways of doing this. BTW, this is a great post for tryCatch in R: https://stackoverflow.com/questions/12193779/how-to-write-trycatch-in-r – RianLauw Mar 09 '21 at 05:20
  • The "R magic" in rpy2 is catching exceptions occurring during the evaluation of the R code block (and just prints them). I can see now that this is a little counterintuitive. An issue report is here: https://github.com/rpy2/rpy2/issues/792 – lgautier Apr 03 '21 at 18:34
  • Thanks for creating the issue report @lgautier. – RianLauw Apr 08 '21 at 03:35

0 Answers0