Reputation: 125
I would like to use the trycatch
function in R to check if the given value is an integer if not return ERROR. My current code looks the following, it doesnt work.
b <- function() as.integer(n_top_features)
tryCatch ( {
error = function(e){
b()
}
},
stop('ERROR: n_top_features variable should be integer!')
)
Upvotes: 0
Views: 105
Reputation: 545488
If you read the documentation of the tryCatch
function, you see the following usage:
tryCatch(expr, ..., finally)
That is: the actual expression you want to “try” is the first argument, and the handlers (which you’ve attempted to write) come afterwards:
tryCatch(
as.integer(n_top_features),
error = function (e) {
stop('ERROR: n_top_features variable should be integer!')
}
)
However, that won’t work either; and the reason is that as.integer
does not raise an error when the argument can’t be converted to an integer. It raises a warning instead. So your tryCatch
needs to install a warning handler:
result = tryCatch(
as.integer(n_top_features),
warning = function (w) {
stop('ERROR: n_top_features variable should be integer!')
}
)
Upvotes: 3