4

I'm going through a beginner programming learning guides and the teacher brings up the try catch block paradigm.

The code you put in the try block is run and if an error happens the code in the catch block is run. Your application should recover from it.

try {
    // do something that might throw an error
}
catch (exceptionError) {
    // handle when it happens
}

I see this working where an application to recover.

Is there paradigm where you can say,

Run this fragment of code but if it doesn't respond in this set amount of time throw an error?

try(10000) {
   // do something that only has a certain amount of time to execute
}
catch (error) {
    log("Task error:"+error);
}
timeout (error) {
    log("Process took too much time");
}

For example,

// give code block ten seconds to error or execute
try(10000) {
    var numberOfTimes = 10,000,000;
    for (var i=0;i<numberOfTimes;i++) {
       drawPolygon(i);
       renderCount++;
    }
    log("Total number of polygons rendered:"+renderCount);
}
timeout(error) {
    log("Total number of polygons rendered:"+renderCount);
}
catch(error) {
    log("Error")
}

I made this example off the top of my head. It's not about the example it's about if this language design feature exists.

3

4 Answers 4

7

There is no popular programming language that would have a built-in timeout system via some keywords like try and catch. (well, there may exist such languages, but not in main stream).

However, it is trivial to implement a timeout when you are writing your own loop (or even an IO operation), Java example:

try{
   long start = System.currentTimeMillis();
   for(i = 0; i< 100000; i++){
      if(System.currentTimeMillis() - start > 10000){
         throw new TimeoutException('Time is up');
      }else {
         // do something that may throw exception (like read/write next N bytes)
      }
   }
}catch(TimeoutException t){
   // handle this
}catch(SomeOtherException e){
   // handle that
}

But, not so when you want to timeout any arbitrary block of code:

  1. Tracking: The CPU must be able to free itself from the code task, and track the time elapsed, in parallel. This brings in a requirement of asynchronous code execution.
  2. Interruptible: The running code must be interruptible. That is: consists of discrete steps where in interrupt check can be done between the steps.

Here, #1 (Tracking) is usually left to the programmers by majority of the programming languages, using constructs like threads, co-routines and event loops. A programmer can just launch another thread/timeout/co-routine to monitor the main task.

But more importantly, #2 (Interruptible) is not always guaranteed since you may be calling some other code that does not respect or support interruption . Meaning the CPU is stuck there and short of killing the process/thread, there is no way out. In short: "arbitrary code" may break out of the constraints.

For #2 (Interruptible) One might even think about terminating the execution itself, however, abruptly stopping (kill) threads and processes is also frowned upon because that may leave things in a corrupted state, incomplete bytes written to IO and more such problems.

Hence, we arrive at the approach taken by mainstream programming languages: Leave it up to the developer to implement timeouts, just provide them the necessary constructs like threads, interrupts etc.

3

I'm not personally aware of any language feature, but this is relatively common in asynchronous libraries. See bluebirdjs promise timeout or monix task timeout, for example. Language designers try to minimize what is actually built into the language. Handling timeouts in the compiler is much more complex than handling them in a library, and the language specification is much more difficult to change than a library API.

You also want to reserve built-in features for those that are truly general purpose, and timeouts are more varied than it might appear at first glance. There's complexity around how and if to cancel the timed out task. If a timeout is coupled with a retry, you might want to vary the timeout with exponential backoff. When you're testing, you want to be able to mock the timeout, so your tests don't take forever. These sorts of concerns are much easier to handle and adapt in a library than when built into the language itself.

1

The example you made requires implicit multithreading that is a little bit too transparent to the developer. Even though modern processors could have many cores multithreading is still something delicate and the developer should always be aware that a piece of code is spawning one or more threads.

3
  • Multithreading is something delicate? Good that you told me. I'll stop using it. Reality check please: In my world, practically everything is multithreaded.
    – gnasher729
    May 16, 2021 at 14:00
  • @gnasher729 Of course everything is multithreaded. But when I write a program I have a rough idea of the number of threads it will create. If I use a thread pool or a parallel collection I know it will create as many threads as the number of available cores allow. If I use a reactive library I know which functions create an extra thread and I always evaluate whether it is worth it. If you write a program that expects the number of active thread at any time to be the double or more of the number of cores you'll waste a lot processing power in overhead.
    – FluidCode
    May 17, 2021 at 12:36
  • @gnasher729 BTW. Your reality check reminds me those who complain about premature optimisation and end with such performance issues that most of the times they sink the entire project.
    – FluidCode
    May 17, 2021 at 12:36
0

“Timeout” is not a feature of any language I know. It would be up to the code you call to detect a timeout and throw an exception which you catch and handle like any other exception.

The problem with “timeout” is that unlike most exceptions it will take considerable time until it happens. So your application must be written to work reasonably well if an exception is thrown a minute after the “try” and it usually cannot just wait for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.