1

I am new to R. Kindly excuse me if it is a basic query. I am facing a strange situation where I am using try catch to catch errors and warnings while sourcing another script. It is working fine also. However, in one particular case, while sourcing, there is an error message followed by a warning message, but try catch in my script is considering it only as a warning message. Please find my code as follows

result1 <- tryCatch ({
source("Path with script.R")
inc_val = 1
},  error = function(er) {
inc_val = 2
} ,  warning = function(er) {
inc_val = 3
},finally = {
})

So in this particular case, result1 is 3 instead of 2, even though there is an error while executing the script.

Kindly let me know where I have done the mistake.

Thanks in advance.

Aravind
  • 11
  • 2
  • There is probably a warning followed by an error. Thus, the warning handler is used (and there is no nested error handling). `tryCatch` is not intended for whole scripts, but for functions (which should be as simple as possible). – Roland Jan 23 '17 at 08:03
  • Thanks Roland for the prompt response. Its actually an error message immediately followed by a warning message( shown in the console ). What would be a good handler while calling whole scripts ? – Aravind Jan 23 '17 at 08:16
  • No, warnings are printed after errors even if they occur first: `fun <- function() {warning("warning"); stop("error")}; fun()`. You can have multiple errors and warnings when executing a script. There is no general or good way to handle that. You need to modify the script itself for the exception handling. – Roland Jan 23 '17 at 08:30
  • You've written "Source" with a capital "S" instead of "s". – Spacedman Jan 23 '17 at 08:34
  • Thanks Roland for the info. I will try to modify the script. Thanks Spacedman for pointing out the spelling mistake, I have made the correction in the post. However that was not the reason for the error or warning. – Aravind Jan 23 '17 at 09:20
  • We can't debug your code without a full example that illustrated your problem. The file you `source` could be doing anything. We'd be guessing,. – Spacedman Jan 23 '17 at 15:08

0 Answers0