Hello. I would like, in the near future, to develop small applications for analyzing some of my physics research. Since some of these applications will be shared among members of my collaboration, these programs should be as error free as possible. Thus, I have looked into error handling. My question is, "When should I use a try / catch statement?". Answers from books range from anytime resources are designated to whenever the programmer feels there may be a problem.
What would be a good practice to adhere to for a semi- beginner in c++ programming. Also, is try/catch the only method for dealing with problems?
Exceptions in general should be used to report errors only in the following cases:
1) The error conditional is indeed exceptional. Something like "My application expects to be able to open its configuration file, but the file didn't exist for some reason". Failure to validate user input is, usually, not an exceptional error condition.
2) The syntax of the language does not provide for a way to propagate an error code in any other way. For example, constructors can't return values, so typically a constructor failure is indicated by throwing an exception. Or any of the operators also can't return error codes because their syntax is generally dictated.
3) In your estimation, you believe that the error that just occurred cannot be handled by the immediate caller of your function that failed, and must be propagated up to a higher level. IMHO, this is a black magic decision, however this is what Sutter and Alexandrescu say in "C++ Coding Standards". Throwing an exception in this case alleviates the caller of having to write explicit code to propagate the error up the call stack.
If your error conditions don't match one of these three, then the suggestion means to report an error is by returning an error code from the function (either via function return value, preferred, or by reference parameter if the function needs to return something else).