### EXCEPTION HANDLING QUESTION

in this code although i have a general catch block but when i try to enter a double value instead of integer one the program runs infinitely what to do???

 ``123456789101112131415161718192021222324252627282930313233343536373839`` `````` ///////////////////////////////////////////////////////////////////////////////////////////////////////// #include using namespace std; void main(){ while(1){ try{ cout<<"Enter the dividend "; int x; cin>>x; cout<<"Enter the divisor "; int y; cin>>y; if(y==0) throw 0; int ans; ans = x /y; cout<<"\nDivision gives result : "<
What I do first is to indent the code to make it readable.
I believe entering a double into an int yields undefined behaviour, so we promote int to double.

 ``12345678910111213141516171819202122232425262728293031323334353637`` ``````#include using namespace std; int main() { while(1) { try { cout<<"Enter the dividend "; double x; cin>>x; cout<<"Enter the divisor "; double y; cin >> y; if(y == 0.) throw 0; int ans; ans = x /y; cout<<"\nDivision gives result : "<
can we also handle exception when user enters values other than this approach
Any way you like.
cin does not throw exceptions by default.
You can do `cin.exceptions(ios::failbit);` to enable exceptions.
Last edited on
i want to say like we are entering values into an int type of variable and the user enters a double type value than we prompt our user that you have entered a wrong value and you should enter an integer value....

CAn we do this if yes than kindly show how to do
Input into a string. Convert to int.
See documentation of std::stoi(std::string &); @ http://en.cppreference.com/w/cpp/string/basic_string/stol

 ``123456789101112131415161718192021222324252627282930313233343536`` ``````#include using namespace std; int main() { while(1) { try { std::string x, y; cout<<"Enter the dividend "; cin>>x; cout<<"Enter the divisor "; cin >> y; if(!std::stoi(y)) throw 0; int ans; ans = std::stoi(x)/std::stoi(y); cout<<"\nDivision gives result : "<
got it THANKS
Topic archived. No new replies allowed.