R function return value as well warning message

Viewed 2687

I called other lib function, which does the calculation and throws warning message. I tried to use tryCatch() to capture the message but do not know how to keep the calculated value and the warning message. Here is sample (simplified) code, I would like mydiv function has both calculated value and warning message. Right now mydiv calls will return the division value or the warning but not both.

mydiv = function(x, y){  
tryCatch({
# raise warning message
if (x > y)
  warning("throw a warning")
  # function calc result
  x/y
}, 
warning = function(war) {
flag = paste("DIV Warning:", war$message)
return (flag)
},
error = function(err) {
 flag = paste("DIV Err", err)   
 return (flag)
})
}

If I call x = mydiv(2, 1) then the x has value "DIV Warning: throw a warning"; if x = mydiv(2, 4) then x: [1] 0.5. So my question is: 1. use tryCatch: how to return the calculated value and warning message if possible; 2. whether there is a better approach to get both values from a function.

1 Answers
Related