Nathan Merrill
Nathan Merrill

Reputation: 8396

Is there such a thing as a try-loop in a programming language?`

I've noticed that a very common pattern in programming is something like the following:

bool continue = true;
while (continue){
   try{
   do something
   break;
   catch(){
   do something else
   }
}

There's a lot of syntax here for 2 lines of real code.

Is there a (somewhat common) programming language that has a try-loop (probably by some other name) that will repeat X while an error is thrown, and can do Y after each error?

Upvotes: 1

Views: 85

Answers (2)

slebetman
slebetman

Reputation: 113994

In tcl you can invent your own syntax (well, not syntax per se, just a control structure, but from the point of view of other languages it looks like inventing syntax):

proc foreach-catch {varname thelist script error_var catch_script} {
    upvar 1 $varname var  ;# link this var to the caller's stack

    foreach var $thelist {
        # uplevel executes code in the caller's stack:
        if {catch {uplevel 1 $script} error_var} {
            uplevel 1 $catch_script
        }
    }
}

Now you can have a catching foreach loop:

# regular foreach looks like this:

foreach x $stuff {
    do-something-with $x
}

# our new foreach-catch looks very similar:

foreach-catch x $stuff {
    do-something-with $x
} error {
    handle-error-condition-for $x -with-error $error
}

Of course, any language that allows you to pass blocks of code or functions around can implement something like this. Here's a javascript example:

function foreach_catch (array,callback,error_callback) {
    for (var i=0;i<array.length;i++) {
        try {
            callback(array[i]);
        }
        catch (err) {
            error_callback(err,x);
        }
    }
}

Which would allow you to do this:

foreach_catch(stuff,
    function(x){
        do_something_with(x);
    },
    function(error,x){
        handle(error,x);
    }
);

Upvotes: 1

user356178
user356178

Reputation:

In C#, you could wrap the try method pattern in a loop which would achieve this goal.

Here's an example with a queue that provides a TryDequeue method that is expected to crash, for instance because it could need to read on an unreliable media (a network or a filesystem).

The DequeueAndThrowExceptionOnErrors method is the part that may throw an exception that you want to isolate from your loop.

int element;
while(myQueue.TryDequeue(out element))
{
    // process element
}

Here's the TryDequeue method from our Queue class.

bool TryDequeue(out int element)
{
    try
    {
        // dequeue logic
        element = DequeueAndThrowExceptionOnErrors();
        return true;
    }
    catch
    {
        // error handling
        element = 0;
        return false;
    }
}

Upvotes: 0

Related Questions