Errors, Warnings, and Messages in R
Understand the three signal types and when each is raised.
The R Condition System
R has a formal condition system for communicating problems. There are three main condition classes: errors (fatal — halt execution), warnings (non-fatal — printed after code finishes), and messages (informational — go to stderr).
# Each condition type behaves differently
message('This is a message')
warning('This is a warning')
# stop() would halt here, so wrap it
tryCatch(stop('This is an error'), error = function(e) print(e))stop() — Generating Errors
stop(msg) signals an error condition. Execution halts immediately and the error message is displayed. It is used inside functions to abort when inputs are invalid or an unrecoverable situation is detected.
divide <- function(x, y) {
if (y == 0) stop('Division by zero is not allowed')
x / y
}
tryCatch(divide(10, 0), error = function(e) cat('Error:', conditionMessage(e), '\n'))
divide(10, 2)All lessons in this course
- Errors, Warnings, and Messages in R
- tryCatch() for Error Recovery
- withCallingHandlers() and Restarts
- Writing Robust Functions with stop() and warning()