Skip to content
Prev 387125 / 398502 Next

Difficulty using the tryCatch() function

try removing the outermost '{'...'}'.  e.g., { warning = ... } should be
'warning = ...'.
----
Adn <- function(x,y) {
    out <- tryCatch(
    {
        x+y
    },
    warning = function(cond) {
        message("There was a warning.")
        message("Here is the original warning message:")
        message(cond)
        return(100)
    },
    error = function(cond) {
        message("There was an error.")
        message("Here is the original error message:")
        message(cond)
        return(200)
    },
    finally = {
        message("Error handling done.")
    }
    )
    if (out==100 | out==200) { z <- 0 }
    else { z <- x+y }
    return(z)
}
(result <- Adn(1,sqrt(2))) # should work fine
(result <- Adn(1,sqrt(-2))) # should catch a warning and set z to 0
(result <- Adn(1,"a")) # should catch an error and set z to 0
Message-ID: <254545.1612726668@apollo2.minshall.org>
In-Reply-To: Your message of "Sun, 07 Feb 2021 14:30:59 -0500." <c5e554c00fb7261ec8844c42d8f1041c@philipsmith.ca>