R S4类的错误处理

R S4类的错误处理,r,s4,R,S4,我是这里的新手。我正在尝试使用S4课程。在我的一些设置方法中,我想获取一个输入值并测试它是否有效。如果它是有效的,我想分配它。如果它无效,我想生成一个可以测试的警告。下面是一个简单的例子: setClass("foo", representation(ind = "numeric")) setGeneric(name="setInd<-",def=function(object,value){standardGeneric("setInd<-")}) setReplaceM

我是这里的新手。我正在尝试使用S4课程。在我的一些设置方法中,我想获取一个输入值并测试它是否有效。如果它是有效的,我想分配它。如果它无效,我想生成一个可以测试的警告。下面是一个简单的例子:

 setClass("foo", representation(ind = "numeric"))

 setGeneric(name="setInd<-",def=function(object,value){standardGeneric("setInd<-")})

 setReplaceMethod(f="setInd",signature="foo",
 def=function(object,value){
   if(is.numeric(value)){
     object@ind<-value;}
   else{
     warning("Foobar")
   }
    return(object)}
 )
setClass(“foo”,表示法(ind=“numeric”))

setGeneric(name=“setInd如果分配失败,我将返回一个错误而不是警告。警告告诉您该过程已完成,但可能会给出意外结果。在您的情况下,该过程将中止:

setReplaceMethod(f="setInd",signature="foo",
 def=function(object,value){
   if(!is.numeric(value))
     stop("Foobar")

   object@ind <- value  
   return(object)}
 )
如果确实需要处理警告,请使用CallingHandlers查看

> withCallingHandlers({setInd(thisFoo)<-"A"},
+     warning = function(w) {print("Hello")})
[1] "Hello"
Warning message:
In `setInd<-`(`*tmp*`, value = "A") : Foobar

>withCallingHandlers({setInd(thisFoo))在这种情况下,赋值违反类定义并生成错误;测试是不必要的。或者,使用
c(“foo”,“numeric”)
作为替换方法的签名,尝试的赋值将再次生成错误(因为没有匹配
c(“foo”,“character”)
)的方法。如Joris所述,使用
tryCatch
捕获错误。
tryCatch(setInd(thisFoo)<-"A",error=function(e){print("Hello")})

> X <- try(setInd(thisFoo) <- "A")
Error in `setInd<-`(`*tmp*`, value = "A") : Foobar
> if(is(X,"try-error")) setInd(thisFoo) <- 5
> thisFoo
An object of class "foo"
Slot "ind":
[1] 5
> withCallingHandlers({setInd(thisFoo)<-"A"},
+     warning = function(w) {print("Hello")})
[1] "Hello"
Warning message:
In `setInd<-`(`*tmp*`, value = "A") : Foobar