AS
exception <-
function(class, msg)
{
cond <- simpleError(msg)
class(cond) <- c(class, "MyException", class(cond))
stop(cond)
}
Here's your function
divideByX <- function(x){
# If x is 0 throws exception
if (length(x) != 1) {
exception("NonScalar", "x is not length 1")
} else if (is.na(x)) {
exception("IsNA", "x is NA")
} else if (x == 0) {
exception("DivByZero", "divide by zero")
}
10 / x
}
and use to generate the output you asked for
lapply(tempList, function(x) tryCatch({
divideByX(x)
}, MyException=function(err) {
conditionMessage(err)
}))
or to treat some exceptions differently from others
lapply(list(NA, 3:5), function(x) tryCatch({
+ divideByX(x)
+ }, IsNA=function(err) {
+ warning(err) # signal a warning, return NA
+ NA
+ }, NonScalar=function(err) {
+ stop(err) # fail
+ }))
Error: x is not length 1
In addition: Warning message:
x is NA