Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8492187
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T22:38:48+00:00 2026-06-10T22:38:48+00:00

I want to write code using tryCatch to deal with errors downloading data from

  • 0

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:

  1. When the URL is wrong, the output will be: "web URL is wrong, can’t get".
  2. When the URL is wrong, the code does not stop, but continues to download until the end of the list of URLs?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T22:38:49+00:00Added an answer on June 10, 2026 at 10:38 pm

    Setting up the code

    urls <- c(
        "http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
        "http://en.wikipedia.org/wiki/Xz",
        "xxxxx"
    )
    
    readUrl <- function(url) {
        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")
    
                suppressWarnings(readLines(url))
                # The return value of `readLines()` is the actual value
                # that will be returned in case there is no condition
                # (e.g. warning or error).
            },
            error = function(cond) {
                message(paste("URL does not seem to exist:", url))
                message("Here's the original error message:")
                message(conditionMessage(cond))
                # Choose a return value in case of error
                NA
            },
            warning = function(cond) {
                message(paste("URL caused a warning:", url))
                message("Here's the original warning message:")
                message(conditionMessage(cond))
                # Choose a return value in case of warning
                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")
            }
        )
    }
    

    Using the code

    > y <- lapply(urls, readUrl)
    This is the 'try' part
    Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
    Some other message at the end
    This is the 'try' part
    Processed URL: http://en.wikipedia.org/wiki/Xz
    Some other message at the end
    This is the 'try' part
    URL does not seem to exist: xxxxx
    Here's the original error message:
    cannot open the connection
    Processed URL: xxxxx
    Some other message at the end
    

    Investigating the output

    > head(y[[1]])
    [1] "<!DOCTYPE html><html><head><title>R: Functions to Manipulate Connections (Files, URLs, ...)</title>"
    [2] "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
    [3] "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\" />"
    [4] "<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/katex@0.15.3/dist/katex.min.css\">"
    [5] "<script type=\"text/javascript\">"
    [6] "const macros = { \"\\\\R\": \"\\\\textsf{R}\", \"\\\\code\": \"\\\\texttt\"};"
    
    > length(y)
    [1] 3
    
    > y[[3]]
    [1] NA
    

    Additional remarks

    tryCatch

    tryCatch returns the value associated to executing expr unless there’s an error or a warning. In this case, specific return values (see NA above) can be specified by supplying a respective handler function (see arguments error and warning in ?tryCatch). These can be functions that already exist, but you can also define them within tryCatch() (as I did above).

    The implications of choosing specific return values of the handler functions

    As we’ve specified that NA should be returned in case of error, the third element in y is NA.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to write a code to backup my Sql Server 2008 Database using
I want to write a .xml file using the following code into the App_Data/posts.
So I am parsing twitter statuses using PHP and I want to write code
I want to write some simple code using DDK - but i don't know
I write a code and using MFC. I want to check if process exists
I want write a little code analyzer which parses nested structures and translates into
I want to write clean code. So When writing a method I want to
I want to write a php code that can search for multiple keywords separated
I want to write a java code that executes some Linux command: String cmd
I want to write a parallel code that works on a 3D matrix where

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.