Errors, Warnings, and Messages in R
Understand the three signal types and when each is raised.
Errors, Warnings, and Messages in R is a free R Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)warning() — Non-Fatal Warnings
warning(msg) signals a warning condition. Unlike errors, warnings do not halt execution — the function continues and the warning is collected. By default warnings are printed after all code finishes, or immediately if options(warn=1) is set.
safe_sqrt <- function(x) {
if (x < 0) {
warning('Negative input; returning NaN')
return(NaN)
}
sqrt(x)
}
result <- safe_sqrt(-4)
cat('Result:', result, '\n')message() — Informational Conditions
message(msg) signals a message condition. It goes to stderr, includes an automatic newline, and can be suppressed with suppressMessages(). Use it for progress updates in functions, not for errors or warnings.
load_data <- function(n) {
message('Loading ', n, ' records...')
seq_len(n)
}
data <- suppressMessages(load_data(100))
cat('Got', length(data), 'records\n')simpleError and simpleWarning Objects
When R creates a condition, it wraps the message in a condition object. simpleError('msg') and simpleWarning('msg') create condition objects manually. You can inspect them with conditionMessage().
e <- simpleError('something went wrong')
w <- simpleWarning('this looks suspicious')
cat('Error class :', class(e), '\n')
cat('Warning class :', class(w), '\n')
cat('Error message :', conditionMessage(e), '\n')
cat('Warning msg :', conditionMessage(w), '\n')conditionMessage() and conditionCall()
conditionMessage(cond) extracts the text message from any condition object. conditionCall(cond) extracts the call that triggered the condition. Both are useful inside error handlers for logging or re-signaling conditions.
tryCatch(
log(-1),
warning = function(w) {
cat('Caught warning :', conditionMessage(w), '\n')
cat('From call :', deparse(conditionCall(w)), '\n')
}
)options(warn = 2) — Treat Warnings as Errors
Setting options(warn = 2) converts all warnings into errors, causing immediate halts. This is useful during development to catch warning-generating code early. Restore with options(warn = 0).
old_warn <- options(warn = 0) # default: collect warnings
log(-1) # just a warning
options(warn = 0)
tryCatch({
options(warn = 2)
log(-1) # now fatal
}, error = function(e) cat('Caught as error:', conditionMessage(e), '\n'),
finally = options(old_warn))Immediate vs Deferred Warnings
With options(warn = 0) (default) warnings are collected and printed at the end. With options(warn = 1) each warning is printed immediately as it occurs. With warn = 2 they become errors.
# warn=1: print warnings immediately as they happen
old <- options(warn = 1)
result1 <- log(-1)
result2 <- sqrt(-4)
cat('Results:', result1, result2, '\n')
options(old)Error vs Warning: Fatal vs Non-Fatal
The critical distinction: an error stops execution entirely unless caught by a handler. A warning is recorded but execution continues. This means bad inputs can silently produce wrong results if you use warnings where you should use errors.
# With warning: execution continues
f_warn <- function(x) { if (x < 0) warning('negative'); x^2 }
cat('warn result:', f_warn(-3), '\n') # still computes 9
# With error: execution stops
f_stop <- function(x) { if (x < 0) stop('negative'); x^2 }
tryCatch(f_stop(-3), error = function(e) cat('stopped:', e$message, '\n'))Nesting Conditions
Conditions can be raised inside other condition handlers. A warning handler can call stop() to upgrade a warning to an error. This is a common pattern for making third-party code stricter.
strict_log <- function(x) {
withCallingHandlers(
log(x),
warning = function(w) {
stop(paste('Strict mode: warning treated as error:', conditionMessage(w)))
}
)
}
tryCatch(strict_log(-1), error = function(e) cat('Error:', e$message, '\n'))
cat('log(4) =', strict_log(4), '\n')suppressWarnings() and suppressMessages()
suppressWarnings(expr) evaluates the expression while silently catching and discarding all warnings. suppressMessages(expr) does the same for message conditions. Use these sparingly — suppressing warnings can hide real problems.
# Without suppression: warning shown
result1 <- log(-1)
# With suppression: warning hidden
result2 <- suppressWarnings(log(-1))
cat('Both are NaN:', is.nan(result1), is.nan(result2), '\n')Quick Check
Which of the following statements about warning() vs stop() is correct?
Conditions: Key Takeaways
Key takeaways for R conditions:
stop()= error = fatal, halts immediately;warning()= non-fatal, execution continues;message()= informational, goes to stderr- All three create condition objects with class hierarchy
conditionMessage(e)extracts the text from any conditionoptions(warn=1)prints warnings immediately;warn=2treats them as errorssuppressWarnings()/suppressMessages()silence conditions- Prefer
stop()for invalid inputs where continuing would be wrong
# Summary of the three condition functions
tryCatch({
message('Step 1 starting')
warning('something looks odd')
stop('cannot continue')
}, message = function(m) cat('MSG:', conditionMessage(m)),
warning = function(w) cat('WARN:', conditionMessage(w), '\n'),
error = function(e) cat('ERR:', conditionMessage(e), '\n'))Frequently asked questions
Is the “Errors, Warnings, and Messages in R” lesson free?
Yes — the full text of “Errors, Warnings, and Messages in R” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.
What will I learn in “Errors, Warnings, and Messages in R”?
Understand the three signal types and when each is raised. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start R Academy?
No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Errors, Warnings, and Messages in R” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this R Academy lesson?
Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
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()