Design Language (Exceptions): Why Try?

In those languages ​​where I saw exceptions (C ++, Java, Javascript, Python, PHP, ...), I always see trysomething like that to highlight the area catch. I wonder if this is necessary. What are the design issues when NOT have tryblocks?

For example, take this:

try{
    try{
        do_something_dangerous0();
    }catch (SomeProblem p){
        handle(p);
    }
    try{
        do_something_dangerous1();
    }catch (SomeProblem p){
        handle(p);
    }
}catch (SomeOtherProblem p){
    handle(p);
}

I present this as an alternative.

do_something_dangerous0();

catch (SomeProblem p){
    handle(p);
}

do_something_dangerous1();

catch (SomeProblem p){
    //catches from only the second unless the first also threw
    handle(p);
}

catch (SomeOtherProblem p){
    //catches from either, because no other block up there would
    handle(p);
}

If you want to avoid blocking too much, you can create a new area:

do_something_dangerous2();

{
    do_something_dangerous3();

    catch (SomeProblem p){
        //does not catch from do_something_dangerous2()
        //because if that throws, it won't reach in here
        handle(p);
    }
}

catch (SomeProblem p){
    handle(p);
}

catch (SomeOtherProblem p){
    handle(p);
}

(My answer is why this will not work for languages ​​like C ++ and Java, at least posted as the answer below, but I have no answer for dynamic languages.)

+3
source share
1 answer

, , .

try , . , , , ++, Objective C Java, catch try, try . try -less .

, ++.

try{
    int x = some_func();
    int y = some_other_func();
}catch(SomeException){
    //...
}

,

int x = some_func();
int y = some_other_func();

catch(SomeException){
    //...
}

x y catch, /.

, catch , (try{\n }\n). , catch, , - try . , -, ( C), .

+4

All Articles