why is "try" necessary

Hi guys,

having read quite a lot of documentation about it, I still can't see clearly why we need to enclose in a try statement the code that needs to be guarded. What does "try" actually do ? Would it not be sufficient to have "throw" and "catch".
Sorry if the question is silly.
try is just the marker for the beginning of the block you want to guard against exceptions. catch is the end symbol for this guarding block and the start of the block that gets called in case of exceptions.

And throw is used (by other functions) inside this block to raise an exception.

It usually looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// actually here, we don't care much when something is wrong
do_something_harmless();
do_something_unimportant();

try // at this point, we really need to know of exceptional cases.
{
    do_something_important();
    do_something_risky();
}
catch( std::bad_alloc )  // ok, we had a problem with out-of-memory. RAM needed ;)
{
    provide_reserve_RAM();
    add_to_shopping_list("4GB RAM");
}
catch( std::logic_error e )  // by convention, errors that is a mistake in the code is logic_error
{
    fire_employee(CHIEF_PROGRAMMER);
}
...


Now "throw" is used within "do_something_important" and "do_something_risky" if they recognize some problem.

1
2
3
4
5
void do_something_important()
{
    if ( we_are_in_wrong_program_state() )
        throw std::logic_error("do_something_important should not be called just now");
}


Note, that some built-in functions also throw exceptions, so sometimes you don't explicit see a "throw" statement in the code and still the code may throw exceptions.


There is another statement "throws" used in function declarations, but you should master the above stuff before you start to look into "throws". If you use "throws" wrongly, it can severly kick you somewhere unpleasant!
Thanks imi,

I kind of gathered that "try" was just a marker, but I wasn't sure.
Now it's clearer.

Topic archived. No new replies allowed.