Hi,
I'm a newbie to c++ and am currently in the exception handling section of the course-ware.
Issue at hand
--------------
Output of following program
Output 1:
Age entered: <age>
After the throw statement
End of program
Output 2:
Age entered: <age>
Error! Invalid Age!
End of program
On running the program, output 1 is obtained when age entered does not satisfy the 'if condition'. However, if age entered is say 120, output 2 (exception to be displayed) is not obtained.
Note: I've also enabled the exception handling feature under tools>compiler options>settings tab>code generation>enable exception handling to YES but still do not get the desired output 2.
Is my header file inclusion wrong and/or does it require additional include which i've missed?
Would much appreciate help from the experts.
Thanks
Sudhir
/*compiler used dev-c++ 4.9.9.2
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
try
{
int age;
cout<<"Enter age (age < 100 or > 1): "<<endl;
cin>>age;
cout<<"Age entered: "<<age<<endl;
if(age>100||age<1)
throw "Invalid Age!";
cout<<"After the throw statement"<<endl;
}
catch(char *msg)
{
cout<<"Error! "<<msg<<endl;
}
cout<<"End of Program: "<<endl;
getch();
return 0;
}*/
As suggested, I added "const" as parameter to the catch function and voila! got the desired output. Thank you!!
Before i mark this topic as solved, could the responder or anyone else please explain adding "const" to "char" as my course book just shows pointer variable msg passed of type char and i thought it had something to do with the inclusion of header file :-).
I think it's because string literals have type of constchar * so you cannot modify it. Since you can't modify it, you must write catch(constchar *msg)
1 2 3 4 5 6 7 8 9 10 11 12 13
// imagine that this is a catch(char *msg) handler
// and you want to modify the original error message inside the handler
void _catch(char *msg)
{
msg[0]='A'; // trying to modify a constant string literral
cout <<msg; // program will crash here
}
int main()
{
_catch("str"); // passing const char* as a parameter, (implicit casting to char *)
return 0;
}