Reputation: 41
I'd like to catch an invalid input error within a timeout error. I wrote the script as follows. However, the timeout didn't work in this case and the program run forever. Could anyone please have a check and let me know how to fix it? Thank you.
for (lb in 1:100) {
rs <- tryCatch(
expr = {
cat("helloworld", "\n");
withTimeout({
rs_son = tryCatch(
expr = {
flag = FALSE
cat("start solnl", "\n");
ret = solnl(X, objfun = obj, confun = con, lb=lb, ub=ub);
cat("finish solnl", "\n");
},
error = function(e) {flag <- TRUE}
)
if(flag) {next}
},
timeout = 10)
},
TimeoutException = function(ex) {
cat("Timeout. Skipping.\n")
}
)
}
To be more clear, this is what I'd like to achieve. The for loop should continue no matter whether this is an invalid input error for the solnl function or timeout error.
Upvotes: 1
Views: 404
Reputation: 6954
There are multiple issues here. First, there is no loop to call next, second, flag
is only defined inside the error handling function, not outside of tryCatch()
, third, the outer tryCatch()
has no impact here.
I added some further cat
messages that hopefully shed some light on what is going on
edit: updated the answer with proper for loop
set.seed(0)
rs <- character()
for (lb in 1:10) {
rs[lb] <- R.utils::withTimeout({
rs_son = tryCatch(
expr = {
flag <- FALSE # has no impact
Sys.sleep(sample(0:2, size = 1))
cat("start solnl", "\n")
ret = solnl(X, objfun = obj, confun = con, lb=lb, ub=ub)
cat("finish solnl", "\n")
},
error = function(e) {
cat(as.character(e))
flag <- TRUE # equals return(TRUE)
}
)
if(rs_son) {
return("NEXT OUT")
}
return("OUT")
},
timeout = 1)
}
#> Error in Sys.sleep(sample(0:2, size = 1)): reached elapsed time limit
#> start solnl
#> Error in solnl(X, objfun = obj, confun = con, lb = lb, ub = ub): could not find function "solnl"
#> Error in Sys.sleep(sample(0:2, size = 1)): reached elapsed time limit
#> start solnl
#> Error in solnl(X, objfun = obj, confun = con, lb = lb, ub = ub): could not find function "solnl"
#> Error in Sys.sleep(sample(0:2, size = 1)): reached elapsed time limit
#> start solnl
#> Error in solnl(X, objfun = obj, confun = con, lb = lb, ub = ub): could not find function "solnl"
#> Error in Sys.sleep(sample(0:2, size = 1)): reached elapsed time limit
#> Error in Sys.sleep(sample(0:2, size = 1)): reached elapsed time limit
#> start solnl
#> Error in solnl(X, objfun = obj, confun = con, lb = lb, ub = ub): could not find function "solnl"
#> start solnl
#> Error in solnl(X, objfun = obj, confun = con, lb = lb, ub = ub): could not find function "solnl"
rs
#> [1] "NEXT OUT" "NEXT OUT" "NEXT OUT" "NEXT OUT" "NEXT OUT" "NEXT OUT"
#> [7] "NEXT OUT" "NEXT OUT" "NEXT OUT" "NEXT OUT"
Upvotes: 1