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:
- 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.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.
- The running code must be interruptible. That isInterruptible: consists of discrete steps where in interrupt check can be done between the steps. 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. "arbitrary code" may break out of the constraints.
NowFor #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 seearrive 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.