Reputation: 781
TryCatch is not printing the warnings unless the warning is wrapped in between brackets.
tryCatch(
{
print(wd)
},
error=function(e){
(warning(sprintf('Watch out %s',e)))}
)
prints the warning ""Watch out Error in print(wd): object 'wd' not found\n"
but
tryCatch(
{
print(wd)
},
error=function(e){
warning(sprintf('Watch out %s',e)) }
)
does not.
Any idea why? How can I fix this? This example is a minimal example. I have a much bigger function that runs through a loop and I don't necessarily want to stop the loop if there is an error but I want to see the warnings.
Upvotes: 0
Views: 121
Reputation: 1055
For your loop you probably want to use message
or cat
, e.g.:
for (i in 1:2)
tryCatch(print(wd),
error = function(e) message(sprintf('Watch out %s',e)))
## Watch out Error in print(wd): object 'wd' not found
##
## Watch out Error in print(wd): object 'wd' not found
To understand what is happening in your two versions:
warning
does not print anything. It signals a warning, which a
handler might print immediately or arrange to be printed later.
If a handler does not execute a non-local transfer of control,
e.g. to a tryCatch
, then ?warning
says this about the value it
returns:
Value:
The warning message as ‘character’ string, invisibly.
If an expression returns a result invisibly, then enclosing it in parentheses makes the result visible. Help files often use the idiom
(x <- foo(y))
to make the result of the assignment visible and have the top level print it.
Upvotes: 1