3 回答

TA貢獻1830條經驗 獲得超3個贊
除了Shane的答案可以將您引向其他StackOverflow討論之外,您還可以嘗試使用代碼搜索功能。此原始答案指向Google的代碼搜索,此后已停止使用,但您可以嘗試
Github搜索,例如在此查詢中以language = R 搜索tryCatch;
Ohloh / Blackduck代碼搜索,例如此查詢R文件中的tryCatch
在整個Debian檔案庫中的Debian代碼搜索引擎
只是為了記錄在案,也有try,但tryCatch可能是可取的。我在Google代碼搜索中嘗試了一下快速計數,但是嘗試為該動詞本身獲取了太多的誤報-但它似乎tryCatch得到了更廣泛的使用。

TA貢獻1786條經驗 獲得超13個贊
基本上,您想使用該tryCatch()功能。查看help(“ tryCatch”)了解更多詳細信息。
這是一個簡單的示例(請記住,您可以執行任何您想做的錯誤操作):
vari <- 1
tryCatch(print("passes"), error = function(e) print(vari), finally=print("finished"))
tryCatch(stop("fails"), error = function(e) print(vari), finally=print("finished"))

TA貢獻2065條經驗 獲得超14個贊
該功能trycatch()相當簡單,并且有很多很好的教程。在Hadley Wickham的書Advanced-R中可以找到R中錯誤處理的出色解釋,其后的內容是一個非?;镜慕榻B,withCallingHandlers()并且withRestarts()用盡可能少的詞:
假設低級程序員編寫了一個函數來計算絕對值。他不確定如何計算,但知道如何構造錯誤并努力傳達自己的天真:
low_level_ABS <- function(x){
if(x<0){
#construct an error
negative_value_error <- structure(
# with class `negative_value`
class = c("negative_value","error", "condition"),
list(message = "Not Sure what to with a negative value",
call = sys.call(),
# and include the offending parameter in the error object
x=x))
# raise the error
stop(negative_value_error)
}
cat("Returning from low_level_ABS()\n")
return(x)
}
一個中級程序員還編寫了一個函數,使用可悲的不完整low_level_ABS函數來計算絕對值。他知道,negative_value 當的值為x負時,低級代碼將引發錯誤,并通過建立允許用戶控制錯誤恢復(或不恢復)的方式來建議解決問題的方法。restartmid_level_ABSmid_level_ABSnegative_value
mid_level_ABS <- function(y){
abs_y <- withRestarts(low_level_ABS(y),
# establish a restart called 'negative_value'
# which returns the negative of it's argument
negative_value_restart=function(z){-z})
cat("Returning from mid_level_ABS()\n")
return(abs_y)
}
最終,高級程序員使用該mid_level_ABS函數來計算絕對值,并建立條件處理程序,該條件處理程序通過使用重新啟動處理程序來告訴 錯誤mid_level_ABS從negative_value錯誤中恢復。
high_level_ABS <- function(z){
abs_z <- withCallingHandlers(
# call this function
mid_level_ABS(z) ,
# and if an `error` occurres
error = function(err){
# and the `error` is a `negative_value` error
if(inherits(err,"negative_value")){
# invoke the restart called 'negative_value_restart'
invokeRestart('negative_value_restart',
# and invoke it with this parameter
err$x)
}else{
# otherwise re-raise the error
stop(err)
}
})
cat("Returning from high_level_ABS()\n")
return(abs_z)
}
所有這些的要點是,通過使用withRestarts()and withCallingHandlers(),該函數 high_level_ABS能夠告訴您mid_level_ABS如何從錯誤引起的low_level_ABS錯誤中恢復而不會停止執行 mid_level_ABS,這是您無法做到的tryCatch():
> high_level_ABS(3)
Returning from low_level_ABS()
Returning from mid_level_ABS()
Returning from high_level_ABS()
[1] 3
> high_level_ABS(-3)
Returning from mid_level_ABS()
Returning from high_level_ABS()
[1] 3
在實踐中,low_level_ABS代表一個mid_level_ABS調用很多(甚至可能數百萬次)的函數,針對錯誤的正確處理方法可能會因情況而異,如何處理特定錯誤的選擇留給了更高級別的函數(high_level_ABS)。
- 3 回答
- 0 關注
- 808 瀏覽
添加回答
舉報