2010-04-12 67 views
94

有没有人有R中异常处理的例子/教程?官方文件非常简洁。R中的异常处理

+1

这也是一个很好的例子:http://stackoverflow.com/q/12193779/2026975。 – imriss 2013-08-14 17:44:35

+0

我发现这篇博文很有用:[http://mazamascience.com/WorkingWithData/?p=912](http://mazamascience.com/WorkingWithData/?p=912) – 2015-06-02 13:05:32

+0

我请求了SO文档主题对于这个问题。 – Leonid 2017-06-01 05:41:40

回答

30

除了Shane的回答指向其他StackOverflow讨论,您可以尝试代码搜索功能。这种原始的回答指出,谷歌的代码搜索已经被停产,但你可以尝试

只是为了记录在案,也有trytryCatch可能是可取的。我在Google代码搜索中尝试过很快计数,但是尝试为动词本身获取太多误报 - 但看起来tryCatch更为广泛。

+0

也许这个例子可以帮助:[http://stackoverflow.com/a/12195574/2026975](http://stackoverflow.com/a/12195574/2026975) – imriss 2013-06-27 14:12:22

+0

A [Github搜索](https:// github。 com/search?q = tryCatch + language%3AR&type = Code&ref = searchresults)可能是不存在链接的替代品。 – Gregor 2014-04-13 03:29:28

58

基本上你想使用tryCatch()函数。查看帮助(“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")) 

看一看这些相关的问题:

+1

第三个链接不是链接。 – Marek 2010-04-13 12:04:51

+8

非Shane的错 - 可以说是正则表达式中的一个错误,用于确定如何标记SO上的内容。 – 2010-04-13 12:18:39

7

重新启动功能在从Lisp继承的R中非常重要。如果你想在循环体中调用一些函数,并且你只是希望程序在函数调用崩溃的时候继续,那么这很有用。试试这个代码:

for (i in 1:20) withRestarts(tryCatch(
if((a <- runif(1))>0.5) print(a) else stop(a), 
finally = print("loop body finished!")), 
abort = function(){}) 
6

函数trycatch()是相当直接的,并且有很多很好的教程。错误R中处理的优异的解释可在哈德利韦翰的书Advanced-R被找到,接下来就是非常基本介绍到withCallingHandlers()withRestarts()在为几句话越好:

比方说一个低水平程序员编写一个函数来计算绝对值 的值。他不知道如何来计算的话,但是他知道how to construct an error和 努力传达自己的幼稚:

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值为负并表明一个解决问题的办法,通过 建立restart,其允许mid_level_ABS用户控制 方式,其中mid_level_ABS复苏(或不)从negative_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()withCallingHandlers(),功能 high_level_ABS能告诉mid_level_ABS如何从错误中恢复 不停止的 mid_level_ABS执行,这是每个人所low_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)。