withTimeout in tryCatch function

Hi,

I'm using the following code to stop an operation if it takes too long and perform another operation instead:

require(R.utils)
tryCatch(
  {
    withTimeout(
      {
        print("hello1")
      }, 
      timeout = 10)
  }, 
  TimeoutException = {
    print("hello2")
  }
)

When I run it, the result is:

[1] "hello2"
[1] "hello1"

I don't think that "hello2" should be returned. Please can you tell me what I am doing wrong?

Thanks.

tryCatch() needs a function for the handlers. Here you are providing an expression, I'm not sure exactly what are the inner mechanics (I would have expected tryCatch to throw an error for incorrect argument). Anyway, you just need to make it a function:

tryCatch(
  {
    R.utils::withTimeout(
      {
        Sys.sleep(1)
        print("hello1")
      }, 
      timeout = 10)
  }, 
  TimeoutException  = function(x){
    print("hello2")
  }
)
1 Like

Thank you, @AlexisW. Btw, it works for me only including function(x). Sys.sleep(1) was not needed.

Yes, that was only to doublecheck that if the sleep time is longer than the timeout, you do get "hello2".

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.