Thanks for the input, but I don't want "try" in the Sweave output. I want
the output to look just like it does in the console, as if an uncaptured
error really did occur.

--sundar

On Mon, Mar 1, 2010 at 11:42 PM, Sharpie <ch...@sharpsteen.net> wrote:

>
>
> Sundar Dorai-Raj-2 wrote:
> >
> > Hi,
> >
> > I'm writing a manual using Sweave and I want to be able to print errors
> > from
> > bad code. Here's an example:
> >
> > <Function-4a>>=
> > MySqrt <- function(x) {
> >   if (missing(x)) {
> >     stop("'x' is missing with no default")
> >   }
> >   if (!is.numeric(x)) {
> >     stop("'x' should only be numeric")
> >   }
> >   if (x < 0) {
> >     stop("'x' should be non-negative")
> >   }
> >   return(sqrt(x))
> > }
> > MySqrt()
> > MySqrt("a")
> > MySqrt(-2)
> > MySqrt(4)
> > @
> >
> > And I would like the output to be:
> >
> > MySqrt <- function(x) {
> > ...
> > }
> >> MySqrt()
> > Error in MySqrt() : 'x' is missing with no default
> >> MySqrt("a")
> > Error in MySqrt("a") : 'x' should only be numeric
> >> MySqrt(-2)
> > Error in MySqrt(-2) : 'x' should be non-negative
> >> MySqrt(2)
> > [1] 1.414214
> >
> > I.e. I want the Error statements to print in the tex file and not just
> > make
> > Sweave to bomb.
> >
> > Thanks,
> >
> > --sundar
> >
>
> You can catch errors in R using the try() function:
>
>  foo <- try( log("A"), silent = TRUE )
>
>  if( class( foo ) == 'try-error' ){
>
>    print( unclass( foo ) )
>
>  }
>
> [1] "Error in log(\"A\") : Non-numeric argument to mathematical function\n"
>
>
> There might be a more clever way to override the default error handling
> that
> would save you from wrapping everything in try()-- but this method should
> work.
>
> Hope it helps!
>
> -Charlie
>
> -----
> Charlie Sharpsteen
> Undergraduate-- Environmental Resources Engineering
> Humboldt State University
> --
> View this message in context:
> http://n4.nabble.com/capturing-errors-in-Sweave-tp1574642p1574686.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help@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.
>

        [[alternative HTML version deleted]]

______________________________________________
R-help@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.

Reply via email to