How to Write Trycatch in R
I Want to Write Trycatch Code to Deal with Error in Downloading from the Web. Url
I want to write trycatch code to deal with error in downloading from the web.
url <- c(
"",
"")
y <- mapply(readLines, con=url)
These two statements run successfully. Below, I create a non-exist web address:
url <- c("xxxxx", "")
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?
5 Answers
Well then: welcome to the R world ;-)
Here you go
Setting up the code
urls <- c(
"",
"",
"xxxxx"
)
readUrl <- function(url) {
out <- tryCatch(
{
# Just to highlight: if you want to use more than one
# R expression in the "try" part then you'll have to
# use curly brackets.
# 'tryCatch()' will return the last evaluated expression
# in case the "try" part was completed successfully
message("This is the 'try' part")
readLines(con=url, warn=FALSE)
# The return value of `readLines()` is the actual value
# that will be returned in case there is no condition
# (e.g. warning or error).
# You don't need to state the return value via `return()` as code
# in the "try" part is not wrapped inside a function (unlike that
# for the condition handlers for warnings and error below)
},
error=function(cond) {
message(paste("URL does not seem to exist:", url))
message("Here's the original error message:")
message(cond)
# Choose a return value in case of error
return(NA)
},
warning=function(cond) {
message(paste("URL caused a warning:", url))
message("Here's the original warning message:")
message(cond)
# Choose a return value in case of warning
return(NULL)
},
finally={
# NOTE:
# Here goes everything that should be executed at the end,
# regardless of success or error.
# If you want more than one expression to be executed, then you
# need to wrap them in curly brackets ({...}); otherwise you could
# just have written 'finally=<expression>'
message(paste("Processed URL:", url))
message("Some other message at the end")
}
)
return(out)
}