开发者

Error Handling with S4 classes

I'm a newbie here. I am trying to use S4 classes. In some of my setting methods, I would like to take an input value and test if it is valid. If it is valid, I would like to assign it. If it is not valid, I would like to generate a warning that can be tested for. Here is a simple example:

 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)}
 )

This generates a warning message when I try to assign a character:

> thisFoo<-new("foo", ind = 2)
> thisFoo
An object of class "foo"
Slot "ind":
[1] 2


> setInd(thisFoo)<-"开发者_如何学JAVAA"
Warning message:
In `setInd<-`(`*tmp*`, value = "A") : Foobar
> thisFoo
An object of class "foo"
Slot "ind":
[1] 2

But I would like to be able to test that the assignment failed. What is a good way of doing this? Thanks.


If the assignment fails, I'd return an error instead of a warning. A warning tells you that the process went through, but might give an unexpected result. In your case, the process is aborted :

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

   object@ind <- value  
   return(object)}
 )

using stop allows you to use tryCatch() or try() constructs. See the relevant help pages for more information. Eg :

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

If you really need to work with warnings, look at withCallingHandlers. Using your original code :

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

Mind you, this is less straightforward to use than the abovementioned options using errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜