err_flag
的值为TRUE
,但是该过程仍然循环并显示“错误”。
完整代码:
while(TRUE) {
tryCatch({
some_result = some_function(some_para)
}, warning = function(war) {
print("warning")
err_flag = TRUE
}, error = function(err) {
print("error")
err_flag = TRUE
} , finally = {
})
if(err_flag) {
break
# break the while loop
}
}
答案 0 :(得分:2)
tryCatch
用于函数式编程。它不是真的适合打破控制流结构。我建议改用try
。
set.seed(1) #for reproducibility
while (TRUE) {
res <- try({
x <- sample(1:5, 1)
if (x == 5) stop("error")
x
}, silent = TRUE)
if (class(res) == "try-error") {
message("breaking loop")
break
} else message(sprintf("The number is %d.", res))
}
#The number is 2.
#The number is 2.
#The number is 3.
#breaking loop