當您手動觸發warning
時,由於您在函數外使用return
,因此表達式也會引發錯誤。
如果您在function(e)
返回錯誤信息本身(而非打印的「錯誤」),這變得更加明顯:(注意,這相當於不包括error
參數)
tryCatch({
1+1
warning("test")
return(2)
}, error=function(e) {
e
})
# <simpleError in doTryCatch(return(expr), name, parentenv, handler):
# no function to return from, jumping to top level>
# Warning message:
# In doTryCatch(return(expr), name, parentenv, handler) : test
這是,如果你在R控制檯輸入return(2)
你會看到相同的錯誤消息:
return(2)
# Error: no function to return from, jumping to top level
進行補救問題,請從您的表達式中刪除return
調用,如下所示:
tryCatch({
1+1
warning("test")
2
}, error=function(e){
print('error')
})
# [1] 2
# Warning message:
# In doTryCatch(return(expr), name, parentenv, handler) : test
不要使用'return'。只要'2'就足夠了。 – jbaums 2014-10-28 19:48:42
@jbaums在意識到我的愚蠢之後,我意識到你的建議完全解決了這個問題,因爲錯誤來自於他們使用函數返回。 – Dason 2014-10-28 19:56:12
非常感謝! – Rentrop 2014-10-28 19:58:14