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!