First: never use your life to continue building. It's useless. tryCatch() will continue if you define a handler for an error or warning. He will use this instead of "default" error=function(e) stop(e) . This will stop your function. If you define a handler (either warning= or error= ), your script will not be stopped, so there is no need to continue.
This says: The correct use of tryCatch in this case would be:
for(i in 1:nrow(symbol)){ tryCatch(prices <- getYahooData(symbol$symbol[i], from, to, freq="daily", type="price"), error = function(e){}) }
or, if you use it in a script and want to go to the next loop when an error occurs, you can simply use:
for(i in 1:nrow(symbol)){ prices <- try(getYahooData(symbol$symbol[i], from, to, freq="daily", type="price"), silent=TRUE) if(inherits(prices,"try-error")) { next } # only true if an error occurs ... # rest of calculations }
If you used this tryCatch method or tried, you would not have the problems that you report here.
Now I can reproduce your case if I use non-existent characters. Your erroneous use of the tryCatch() function is causing problems. read.table returns an error ( Error in file(file, "rt") : cannot open the connection ). This is a mistake , not a warning. You will receive an additional warning that the 404 file was not found.
When a warning is issued along with an error, the function of the warning handler is first processed. This is because before a function can be stopped, a warning must be raised. Thus, it will not handle the error received , which means that on.exit(close(file)) in read.table() will not be called. Therefore, the connection is not closed correctly and is still considered open, although it can no longer be found using R (showAllConnections () shows nothing). Since the error is not addressed, something is wrong in registering the connection. Since the connection cannot be opened, on.exit(close(...)) will have no effect. showConnections() does not show the connection, but for some reason R is still thinking about it. Consequently, all hell breaks and you break your R.
thanks for the corrections @Tommy
A simple code example to illustrate this:
myfun <- function(x){ if(x>1) warning("aWarning") stop("aStop") x } tryCatch(myfun(0.5), warning=function(w)print("warning"), error=function(e) print("stop")) [1] "stop" tryCatch(myfun(1.5), warning=function(w)print("warning"), error=function(e) print("stop")) [1] "warning"
In short:
- Check the characters used. They are probably mistaken.
- never use a warning handler if you expect errors.
And as an extra: your loop will return the result of the last call, as you overwrite prices every time you go through the loop, in case you used the correct characters.
Edit: in case you want to continue the action