R语言捕获错误

tryCatch语法

R语言中捕获错误的方法。

基本语法:

result = tryCatch(
{
	# 主体表达式,存在于花括号中
    expr
}, 
# 捕获warning,执行warning韩式,参数为warning信息
warning = function(warning_condition) {
    warning-handler-code
}, 
# 捕获error,执行error函数,参数为error信息
error = function(error_condition) {
    error-handler-code
}, 
# 总是执行的最后表达式,一般执行清理操作
finally={
    cleanup-code
})

实例

下面以一个实例来说明。

urls <- c(
    "http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
    "http://en.wikipedia.org/wiki/Xz",
    "xxxxx"
)
readUrl <- function(url) {
    out <- tryCatch(
        {
            # Just to highlight: if you want to use more than one 
            # R expression in the "try" part then you'll have to 
            # use curly brackets.
            # 'tryCatch()' will return the last evaluated expression 
            # in case the "try" part was completed successfully

            message("This is the 'try' part")

            readLines(con=url, warn=FALSE) 
            # The return value of `readLines()` is the actual value 
            # that will be returned in case there is no condition 
            # (e.g. warning or error). 
            # You don't need to state the return value via `return()` as code 
            # in the "try" part is not wrapped insided a function (unlike that
            # for the condition handlers for warnings and error below)
        },
        error=function(cond) {
            message(paste("URL does not seem to exist:", url))
            message("Here's the original error message:")
            message(cond)
            # Choose a return value in case of error
            return(NA)
        },
        warning=function(cond) {
            message(paste("URL caused a warning:", url))
            message("Here's the original warning message:")
            message(cond)
            # Choose a return value in case of warning
            return(NULL)
        },
        finally={
        # NOTE:
        # Here goes everything that should be executed at the end,
        # regardless of success or error.
        # If you want more than one expression to be executed, then you 
        # need to wrap them in curly brackets ({...}); otherwise you could
        # just have written 'finally=<expression>' 
            message(paste("Processed URL:", url))
            message("Some other message at the end")
        }
    )    
    return(out)
}

执行实例

y <- lapply(urls, readUrl)
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Some other message at the end
Processed URL: http://en.wikipedia.org/wiki/Xz
Some other message at the end
URL does not seem to exist: xxxxx
Here's the original error message:
cannot open the connection
Processed URL: xxxxx
Some other message at the end
Warning message:
In file(con, "r") : cannot open file 'xxxxx': No such file or directory

查看结果

> head(y[[1]])
[1] "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"      
[2] "<html><head><title>R: Functions to Manipulate Connections</title>"      
[3] "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
[4] "<link rel=\"stylesheet\" type=\"text/css\" href=\"R.css\">"             
[5] "</head><body>"                                                          
[6] ""    

> length(y)
[1] 3

> y[[3]]
[1] NA

外记

  • 当没有错误或警告时,tryCatch返回expr表达式的结果值。
  • 当出现错误或警告时,可以通过提供相应的处理函数来指定特定的返回值(如error中的return(NA))(详细请见?tryCatch中的参数error和warning)。
  • 抑制warning的可替换的方法:suppressWarnings(readLines(con=url))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
R语言中的condition是指在代码执行过程中可能出现的异常、警告或消息。condition可以由系统函数如stop()、warning()、message()生成,也可以由用户自定义函数生成。可以使用tryCatch()和withCallingHandlers()函数来处理condition。 tryCatch()函数提供了一种捕获condition并执行相应处理代码的机制。在tryCatch()函数中,可以指定error、warning和message处理函数,分别用于处理错误、警告和消息。当condition发生时,相应类型的处理函数将被调用。 withCallingHandlers()函数也提供了处理condition的机制,可以指定warning和message处理函数。与tryCatch()不同的是,withCallingHandlers()函数不处理错误,只处理警告和消息。 无论是tryCatch()还是withCallingHandlers(),处理函数中的代码将在condition发生时被执行。使用conditionMessage(cnd)可以获取condition的输出信息。 需要注意的是,tryCatch()只捕获一次condition,而withCallingHandlers()可以捕获多次condition。处理函数的执行顺序是从内层处理函数开始,向外扩展到外层处理函数,这种机制被称为bubbling up处理机制。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [R语言的状况处理(Conditions Handling)](https://blog.csdn.net/ofoliao/article/details/102616323)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值