I'm just learning how to use exceptions in C++ and have come across weird behavior in my "test" code. (excuse overly stupid questions like this one, please...it's NOT lack of research/effort, just lack of experience!) If I'm catching just the exception DivideByZero
it works fine.
But introducing the second exception StupidQuestion
makes the code not work exactly how I expected. How I wrote it below I thought it should take care of the DivideByZero
exception if it needs to, and if not then check if StupidQuestion
occurs, and if not just go back to the try
clause and print the normal result. But if I input, say, a=3
and b=1
, the program redirects to the DivideByZero
try
clause instead of the StupidQuestion
one. The weird thing is, though, divide
does seem to be throwing StupidQuestion
(see via cout
statement), but it's not catching right, as also seen by the absense of the cout
statement.
#include <iostream>
#include <cstdlib>
using namespace std;
const int DivideByZero = 42;
const int StupidQuestion=1337;
float divide (int,int);
main(){
int a,b;
float c;
cout << "Enter numerator: ";
cin >> a;
cout << "Enter denominator: ";
cin >> b;
try{
c = divide(a,b);
cout << "The answer is " << c << endl;
}
catch(int DivideByZero){
cout << "ERROR: Divide by zero!" << endl;
}
catch(int StupidQuestion){
cout << "But doesn't come over here...?" << endl;
cout << "ERROR: You are an idiot for asking a stupid question like that!" << endl;
}
system("PAUSE");
}
float divide(int a, int b){
if(b==0){
throw DivideByZero;
}
else if(b==1){
cout << "It goes correctly here...?" << endl;
throw StupidQuestion;
}
else return (float)a/b;
}
I was wondering if it had something to do with the fact that DivideByZero
and StupidQuestion
were both of type int
, so I changed the code to make StupidQuestion be of type char instead of int. (So: const char StupidQuestion='F';
and catch(char StupidQuestion)
were really the only things changed from above) And it worked fine.
Why isn't the above code working when the two exceptions have the same type (int
)?