Functions and Errors
tryCatch
Handling Conversion
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 = "")
value ← 12x
1value <- "12x"2number <- tryCatch(as.numeric(value), warning = function(w) NA)values this step12xvaluewarning 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 handlerNAnumber12xvaluestatus ← bad
2number <- tryCatch(as.numeric(value), warning = function(w) NA)3status <- ifelse(is.na(number), "bad", "ok")4cat(status, "\n", sep = "")values this stepbadstatusNAnumbercat(status, " ", sep = "")
3status <- ifelse(is.na(number), "bad", "ok")4cat(status, "\n", sep = "")outputbadvalues this stepbadstatus
Follow the Fallback
valuestarts as12x.as.numeric(value)warns because12xis not a clean number.tryCatchruns the warning handler.- The handler returns
NA, sonumberbecomesNA. ifelse(is.na(number), "bad", "ok")makesstatusequalbad. | 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.