[R] help: error handling in try

jim holtman jholtman at gmail.com
Wed Sep 10 14:11:57 CEST 2008


Why don't you use 'try' in this fashion:

> f.error <- function(x) if (x == 1) stop('error')
>
> value <- try(f.error(1))
Error in f.error(1) : error
> if (inherits(value, 'try-error')) cat("Got this error:", value) else print ("no error")
Got this error: Error in f.error(1) : error
> value <- try(f.error(0))  # no error
> if (inherits(value, 'try-error')) cat ("Got this error:", value) else print("no error")
[1] "no error"
>
>


On Tue, Sep 9, 2008 at 8:56 PM, Andy Zhu <andyzhu35 at yahoo.com> wrote:
> First time to post and searched archive for this problem with no clue. My version is 2.5.1.
>
> Below is a function to check if a given date is a valid date to a given date function object. It uses try (also tried tryCatch but with same problem). When given an invalid date, I am hoping try will generate en error message which would be picked up by the geterrmessage and thus expecting a false result. but this is not the case when it is inside a function. However, if simply run the body of function, the ret is indeed a false value. Why are they different?
>
> Many thanks
>
>
> is.Date=
> # adate: a scalar value
> # fun: the date function object
> # format: the designated date format to date function
> function(adate,fun,format) {
>         ret=NA;
>         error.old=geterrmessage();
>         .Internal(seterrmessage('no error'));
>         try(fun(adate,format),silent=T);
>         error=geterrmessage();
>         if (error=='no error') {
>                 ret=T;
>         } else {
>                 ret=F;
>         }
>         .Internal(seterrmessage(error.old));
>         return(ret);
> }
>
> adate='12/2000';
> fun=as.Date;
> format='%b %Y';
>
> is.Date(adate,fun,format) # returns true which is not correct.
>
>         ret=NA;
>
>         error.old=geterrmessage();
>
>         .Internal(seterrmessage('no error'));
>
>         try(fun(adate,format),silent=T);
>
>         error=geterrmessage();
>
>         if (error=='no error') {
>
>                 ret=T;
>
>         } else {
>
>                 ret=F;
>
>         }
>
>         .Internal(seterrmessage(error.old));
>
>
> ret # shows false which is correct
>
>
>
>
>        [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list