捕获特定异常

异常处理

check_data <- function(data) {
  if (is.null(data)) {
    stop(errorCondition("data is NULL",
                        class = "IsNullError"))
  }
  if (length(data) == 0) {
    stop(errorCondition("data is empty",
                        class = "IsEmptyError"))
  }
}

# One handler per condition class
msg <- tryCatch(
  check_data(integer(0)),
  IsNullError = \(e) "vector is not specified",
  IsEmptyError = \(e) "vector is empty")
# msg = vector is empty

cat("msg =", msg, "\n")