R中的tryCatch语法

时间:2015-07-17 17:38:48

标签: r try-catch

在我收到错误后,无法理解为什么hasRaised $ status仍为零。

setAnswer <-function(n){stop("Wrong Answer")}

hasRaised = list(status=0, e_message = "") 
tryCatch(setAnswer(42),
    error = function(e) {print(e$message); hasRaised$status = 1; hasRaised$e_message = e$message;}) 
if(hasRaised$status==0){stop("FailedToRise_getAnswer")}

如何修改&#34;全球&#34;错误函数的变量?

1 个答案:

答案 0 :(得分:0)

您可以拆分错误消息,并使用tryCatch函数中的finally参数。见下文:

setAnswer <-function(n){stop("Wrong Answer")}

hasRaised = list(status=0, e_message = "") 

tryCatch(setAnswer(42),
     error = function(e) print(e$message), 
     finally = {hasRaised$status = 1; hasRaised$e_message = e$message;}) 

if(hasRaised$status==0){stop("FailedToRise_getAnswer")}