I want to write code using tryCatch to deal with errors downloading data from the web.
url <- c(
"http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
"http://en.wikipedia.org/wiki/Xz")
y <- mapply(readLines, con=url)
These two statements run successfully. Below, I create a non-exist web address:
url <- c("xxxxx", "http://en.wikipedia.org/wiki/Xz")
url[1] does not exist. How does one write a tryCatch loop (function) so that:
- When the URL is wrong, the output will be: "web URL is wrong, can’t get".
- When the URL is wrong, the code does not stop, but continues to download until the end of the list of URLs?
Setting up the code
Using the code
Investigating the output
Additional remarks
tryCatchtryCatchreturns the value associated to executingexprunless there’s an error or a warning. In this case, specific return values (seeNAabove) can be specified by supplying a respective handler function (see argumentserrorandwarningin?tryCatch). These can be functions that already exist, but you can also define them withintryCatch()(as I did above).The implications of choosing specific return values of the handler functions
As we’ve specified that
NAshould be returned in case of error, the third element inyisNA.