Using try catch vs do while loops in C++

  • Context: C/C++ 
  • Thread starter Thread starter CFDFEAGURU
  • Start date Start date
  • Tags Tags
    C++ Loops
Click For Summary

Discussion Overview

The discussion revolves around the use of try-catch exception handling versus do-while loops for managing user input in C++. Participants explore the implications of each approach, particularly in the context of error handling and user input validation.

Discussion Character

  • Debate/contested
  • Technical explanation
  • Conceptual clarification

Main Points Raised

  • One participant describes a method for handling user input using a do-while loop, which prompts the user until valid input is received.
  • Another participant advocates for using try-catch blocks to handle user input, especially to manage cases where non-numeric input is provided.
  • Some participants express concerns about the unpredictability of type casting and suggest using libraries like boost for safer type conversions.
  • There is a viewpoint that exceptions should be reserved for exceptional cases rather than regular user input handling.
  • One participant argues that user input errors are common and should not be treated as exceptional, suggesting that reprompting for input is a more straightforward solution.
  • Another participant agrees that handling user input errors directly in the main code flow is appropriate, while reserving exceptions for more serious errors that disrupt program execution.

Areas of Agreement / Disagreement

Participants express differing opinions on whether user input errors should be handled with exceptions or through direct input validation methods. There is no consensus on the best approach, as multiple competing views remain.

Contextual Notes

Some participants highlight the limitations of the standard library for safely converting between types, suggesting that additional libraries may be necessary for robust error handling.

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
 

Similar threads

Replies
11
Views
4K
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
4K
Replies
2
Views
2K
  • · Replies 16 ·
Replies
16
Views
5K
  • · Replies 7 ·
Replies
7
Views
7K
  • · Replies 4 ·
Replies
4
Views
11K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
15
Views
5K
  • · Replies 6 ·
Replies
6
Views
2K