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).