0

I'm having now such curiosity: in a C++ software, when should a put some code inside a try-catch system and when not? I aware that it's not actually advisable to implement try-catch around all the code inside all methods of one's software (this link have some explanations) and I know that there are some situations when to implement try-catch is a good idea, such as:

  • When there is a mathematical division of one variable by other (or a result of a multiplication) that could possibly result in a "division by zero" situation;
  • When one uses classes that throws something when failures occur (not my situation, since I use Qt which don't work with throw-catch, rather returning false when error occurs or settings false to a pointer to a boolean variable);
  • When a cast is perform that could result in a failed cast

And of course, one could use try-catch as a way to organize counter-problems logic and log writing, such as e.g.:

myMethod()
{
    //One way
    if (!returnsBooleanMethod())
    {
        printf("An error occured!");
    }
    else
    {
        //do something
    }

    //Another way
    try
    {
        if (!returnsBooleanMethod())
            throw "";

        //do something
    }
    catch (...)
    {
        printf("An error occured!");
    }
}

And, well, I guess that the choice between the two possible ways described above is a matter of developer's and company's preference.

Is there any other situation when try-catch system should be implemented in C++?

EDIT

My question was marked as a duplicate of Usage of try/catch blocks in C++, which, in my opinion, was a bad action: my question is different from that one since it's regarding only and specifically when should I use/it's recommended to use try-catch, while that other (despite the title and one of the 3 "subquestions") deals more with a particular try-catch implementation described by the author and try-catch speed efficiency (as its answers clearly points).

Community
  • 1
  • 1
Momergil
  • 2,213
  • 5
  • 29
  • 59
  • 4
    Rule of thumb: only throw if you *can't* handle a failure locally; only catch if you *can* handle a failure locally. – Mike Seymour Jul 18 '14 at 13:34
  • Just don't do [Pokémon Exception Handling](http://blog.codinghorror.com/new-programming-jargon/) – Marco A. Jul 18 '14 at 13:37
  • 1
    I rcommended reading from Stroustrup about the advantages of exception handling: http://www.stroustrup.com/bs_faq2.html#exceptions-why It's especially usefull for catching unexpected error accross serveral layers of function/member calls so that the errors do not need to be handled at each level, but only at the level where the it's meaninful dor your app. – Christophe Jul 18 '14 at 13:44

0 Answers0