C/C++ Using try catch vs do while loops in C++

  • Thread starter Thread starter CFDFEAGURU
  • Start date Start date
  • Tags Tags
    C++ Loops
AI Thread Summary
The discussion centers around the use of try-catch exception handling versus do-while loops for managing user input in C++. The original poster, Matt, shares a function that prompts users for a tube outer diameter, ensuring valid input through a loop that repeats until the user provides a positive value. He questions whether using try-catch for exception handling would be a better approach, particularly for cases where users might input invalid types, such as strings instead of numbers.Responses emphasize that user input errors are common and should be handled directly within the main program logic rather than through exceptions, which are better suited for truly exceptional cases. It is suggested that using try-catch can complicate code, especially when converting types, and that libraries like boost::lexical_cast can provide safer type conversions. Overall, the consensus is that while exceptions have their place, handling user input errors with loops is a more straightforward and effective method.
CFDFEAGURU
Messages
781
Reaction score
10
Hello all,

First let me state the following:

1. The programs that I write are not production code.
2. I am not a trained developer.
3. I do not work for a software development company.

My question pertains to the use of try catch exception handling vs. using do while loops.

Currently, I screen all user input in the following manner.

Below is an example of a simple user input function named, tube_od(), this function simply asks the user for the tube od in inches, converts the od to meters. If the tube od has been entered as a zero or negative value the output to the user is "Invalid Entry" and the question is repeated until the proper conditions are met.

Code:
void tube_od(){
// Obtain the tube outer diameter in inches
	do{
		printf("Tube OD (inches) ");
		getline(cin,s);
		XDO = string_number<double>(s);
		XDO = XDO*0.0254;	// Convert inches to meters.
		if(XDO <= 0) cout << "Invalid Entry" << endl;
	}while(XDO <= 0);
}

Here is the function string_number()

Code:
template <typename T>
// Templated function used to obtain the correct user
// input. All user input comes in as a text string and
// then is converted by this function to the appropriate
// typedef.
  T string_number (const string &Text)
  {
     istringstream ss(Text);
     T result;
     return ss >> result ? result : -1;
  }

The above method works fine but I was wondering if it would be better to use a try catch statement and take advantage of the C++ exception and error handling.

I would appreciate any comments.

Thanks
Matt
 
Technology news on Phys.org
I normally use Try/Catch for things similar to what you are doing but to also include the cases where the user enters things like strings instead of the expected numbers. Type casting can yield sometimes unpredictable results that can throw errors, or worse not throw an exception but give you a garbage output. You can define your own exceptions as well if you want to be more specific than just what the compiler throws at you. I would use a try/catch block anytime you are working with user input.
 
Experience shows that attempting to write exception-safe code where the try{} block includes casts between strings and number types is insane without using one of the boost casts. There simply isn't enough contained within the standard library to do such things safely.

If you find yourself needing to convert between types in this way, boost::lexical_cast provides everything you need - safely!
 
You should (usually) reserve exceptions for exceptional cases (errors) rather than regular program logic.
 
You should (usually) reserve exceptions for exceptional cases (errors) rather than regular program logic.

That is the rule that I follow.

I was just curious to know what some other programmers thoughts were on the subjcect of exceptions.

Experience shows that attempting to write exception-safe code where the try{} block includes casts between strings and number types is insane without using one of the boost casts. There simply isn't enough contained within the standard library to do such things safely.

If you find yourself needing to convert between types in this way, boost::lexical_cast provides everything you need - safely!

Thanks! That I didn't know.

Thanks
Matt
 
CFDFEAGURU said:
I was just curious to know what some other programmers thoughts were on the subjcect of exceptions.
My opinion: User input errors are anything *but* exceptional. They are in fact quite common.
 
In the case of user input errors, the normal solution is to reprompt the user for another input, remaining within the main line code to handle that input.

In the case of a "real" error, the program can't continue normally and so exception handling makes more sense.

In some cases, a program selects a method based on what is available on a system. For example a program could test to see if direct X version 10 was installed, and if not, check to see if version 9 (or lower) was available and setup for that. In my case, I generally deal with stuff like this by using pointer to functions (or overriding member functions) so that the main line code remains the same and the differences are dealt with inside the functions being called.
 
In the case of user input errors, the normal solution is to reprompt the user for another input, remaining within the main line code to handle that input.

That is exactly what my programs will do when the user input is not within the parameters that I have specified for that input.

In the case of a "real" error, the program can't continue normally and so exception handling makes more sense.

I agree and currently that is what my programs will do.

Thanks for you input Jeff Reid it is greatly appreciated.

Matt
 
Back
Top