Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
# stop() and warning() — signal conditions safe_sqrt <- function(x) { if (!is.numeric(x)) stop("x must be numeric") if (any(x < 0)) warning("negative values will produce NaN") sqrt(x) } safe_sqrt(c(4, 9, 16)) # 2 3 4 safe_sqrt(c(4, -1)) # warning + NaN result # tryCatch — catch errors result <- tryCatch({ log(-1) # produces NaN with a warning "success" }, warning = function(w) { cat("Caught warning:", conditionMessage(w), " ") NA }, error = function(e) { cat("Caught error: ", conditionMessage(e), " ") NA }) result # NA (the warning handler returned NA) # tryCatch around a real error tryCatch( stop("something went wrong"), error = function(e) paste("Handled:", conditionMessage(e)) ) # withCallingHandlers — log and continue withCallingHandlers({ message("Step 1 complete") warning("Minor issue at step 2") 42 # final value }, message = function(m) { cat("[MSG]", conditionMessage(m)) invokeRestart("muffleMessage") }, warning = function(w) { cat("[WARN]", conditionMessage(w), " ") invokeRestart("muffleWarning") }) # stopifnot — assert preconditions divide <- function(a, b) { stopifnot(is.numeric(a), is.numeric(b), b != 0) a / b } divide(10, 2) # 5 # divide(10, 0) # Error: b != 0 is not TRUE
Result
Open