r无法使用trycatch打破while循环

时间:2018-11-27 10:14:25

标签: r

err_flag的值为TRUE,但是该过程仍然循环并显示“错误”。

enter image description here

完整代码:

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
     } 
}

1 个答案:

答案 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