rimagepixmap

Problems with tryCatch()


I'm trying to built a script in R that looks like this:

randomlist <- list(x=ran1, y=ran2) #{x,y}
contour <- Conte(c(round(randomlist$x),round(randomlist$y)),img@grey)
#if Conte function returns me an error, then get new randomlist values
#Do until it doesn't returns an error

The functions returns the coordinates of a contour image if the random {x,y} are inside a region of the image. I know that maybe this is kind of dumb and not so clear question but I'm not good at R and the error handling is a mess for me. I tried with tryCatch() but I can't figure out how to apply it. Thank you very much!


Solution

  • Reproducible code would help. I usually handle these sorts of problems with try e.g:

    temp <- function(N) {
      if (N < 0) stop("Error")
      return(N)
    }
    
    out <- 0 
    n <- 0 
    out <- try(temp(rnorm(1)))
    while(class(out) == "try-error") {
     n <- n + 1
     print(n) 
     out <- try(temp(rnorm(1))) 
    }  
    out