In order to set up a coherent exception handling interface for my colleagues' and my R scripts, I would like to employ the following tryCatch structure.
- An outer tryCatch is wrapped around a given R script. It is used to catch and handle fatal errors that require the script to abort.
- User-specific tryCatch commands within the user's scripts. These should catch and, possibly, handle
- 2a. non-fatal errors, where no script abortion is necessary
- 2b. fatal-errors that require the script to abort. The error is handled by the outer tryCatch [see 1.]
- 2c. fatal-errors with additional error information. Error handled by outer tryCatch.
The following code is how I would implement these features. However, since I am not an expert in R, I would like to ask whether this is a good approach. Specifically:
Q1. Is it ok not to specify an error handler in the inner tryCatch and to wait for the outer tryCatch to handle that error (see 2b. above and code below)?
Q2. Is rethrowing the same error (see 2c. above/below) within a handler correct/considered good coding style?
Thank you!
#outer tryCatch, see 1.
tryCatch({
#user code block
#2a. user specific tryCatch, object "vec" not defined
tryCatch(print(vec),error=function(e) {print("Non-fatal error. Script execution continued.");print(e);})
#2b. user specific tryCatch
tryCatch(vec*2)
#2c. user specific tryCatch
tryCatch(vec*parameter1, error=function(e) {print("Additional fatal error information. Script execution aborted.");stop(e);})
#end of user code block
},
#outer tryCatch error handler in order to handle fatal errors
error=function(e) {print("Fatal error");print(e);}
)