我正在尝试使用 tryCatch 函数来捕获错误并停止运行,并打印个性化和原始的错误消息。该表达式是对a+"T"求值,这肯定会产生错误。代码会是这样的
a <- 1
res <- tryCatch({a+"T"},
error = function(e) {stop(); print("We get the following errors:"); print(Original_message)})
但是这段代码不起作用。我们如何才能同时完成这三件事?
例如像这样的东西:
a <- 1
res <- tryCatch(
a+"T",
error = function(e) cat("We get the following errors:\n", e$message)
)
We get the following errors: non-numeric argument to binary operator
或者也许是这样的:
res <- tryCatch(
a+"T",
error = function(e) stop("We get the following errors:\n", e, call. = FALSE)
)
Error: We get the following errors: Error in a + "T": non-numeric argument to binary operator
如果您在错误函数开始时调用
stop()
,评估将立即停止,并且函数的其余部分不会运行。错误本身 (e
) 包含调用 (e$call
) 和错误消息 (e$message)
。 print(e)
将显示两者。