Nakilon
Nakilon

Reputation: 35092

Jump out of "try-catch"?

Is there a language with a keyword to jump out of try-catch block?

For example, there is a walkaround in Ruby:

lambda {
    begin
        p 0
        break
        p 1
    rescue
        p 2
    end
}.call
p 3

It's also (I believe) possible in Javascript.
But I want a way without anonymous function (to avoid indentation) – like if break or continue were possible.

I know, that C/C++/C# languages allow using goto.

Do languages with another approach exist?

Upvotes: 2

Views: 1958

Answers (3)

Óscar López
Óscar López

Reputation: 236124

Using continuations, you can jump out of any part in the code. For instance, with call-with-current-continuation in Scheme. This example from wikipedia illustrates the basic concept:

(define (f return)
  (return 2)
  3)

(display (f (lambda (x) x))) ; displays 3

(display (call-with-current-continuation f)) ; displays 2

In general, a continuation can be used to escape from any point in the execution of a procedure (they're not limited to try/catch blocks), no matter how deeply nested it is - in that regard, it's a more general construct than an Exception or a goto, as both of those constructs can be implemented in terms of continuations.

At first, continuations are not an easy-to-grasp concept, but with practice they can be very useful, see this paper detailing the many possible applications of continuations.

Upvotes: 1

deceze
deceze

Reputation: 522499

So basically it sounds like you're asking for a goto equivalent to skip the execution of particular parts of your code. Something like:

foo();
if (!bar) {
    goto end;
}
baz();

end:
print "ended";

I won't go into pros and cons of gotos, but they're not available in a number of languages for various reasons. You can virtually always formulate your code like below for the same effect though:

foo();
if (bar) {
    baz();
}

print "ended";

This obviously also works when you're actually using exceptions:

try {
    foo();
    if (bar) {
        baz();
    }
} catch (Exception e) {
    help();
}

print "ended";

It has the same effect of skipping the execution of a particular branch of code under certain circumstances and is the standard way to do it. I cannot really imagine a situation where breaking out of a try..catch or using an equivalent goto would offer any advantage.

Upvotes: 0

secretformula
secretformula

Reputation: 6432

You could always just throw a known exception which you catch but do nothing with. In c#

try {
    if(true)
        throw new GetOutException();
}
catch(GetOutException e) {
}
catch(Exception e) {
    // Do something here    
}

Upvotes: 1

Related Questions