tryCatch lets a script choose a fallback when an expression warns or errors.

Program

Play the script to see invalid text trigger the warning handler and become a fallback value.

try_catch.R
Replay: real traced execution (multi-file project)
value <- "12x"
number <- tryCatch(as.numeric(value), warning = function(w) NA)
status <- ifelse(is.na(number), "bad", "ok")
cat(status, "\n", sep = "")
  1. value ← 12x

    1value <- "12x"2number <- tryCatch(as.numeric(value), warning = function(w) NA)
    values this step12xvalue
  2. warning handler ← NA, number ← NA

    1value <- "12x"2number <- tryCatch(as.numeric(value), warning = function(w) NA)3status <- ifelse(is.na(number), "bad", "ok")
    values this stepNAwarning handlerNAnumber12xvalue
  3. status ← bad

    2number <- tryCatch(as.numeric(value), warning = function(w) NA)3status <- ifelse(is.na(number), "bad", "ok")4cat(status, "\n", sep = "")
    values this stepbadstatusNAnumber
  4. cat(status, " ", sep = "")

    3status <- ifelse(is.na(number), "bad", "ok")4cat(status, "\n", sep = "")
    outputbad
    values this stepbadstatus

Follow the Fallback

  1. value starts as 12x.
  2. as.numeric(value) warns because 12x is not a clean number.
  3. tryCatch runs the warning handler.
  4. The handler returns NA, so number becomes NA.
  5. ifelse(is.na(number), "bad", "ok") makes status equal bad. | step | value | | --- | --- | | value | 12x | | warning handler | NA | | number | NA | | status | bad | | stdout | bad |
tryCatch `tryCatch` handles warnings or errors from an expression.
as.numeric `as.numeric(value)` warns when text is not a clean number.
fallback The warning handler returns `NA`, then the script labels the row `bad`.

Exercise: try_catch.R

Reproduce the output bad, then trace how value 12x becomes number NA and status bad.