For the past few years I've been learning c++ but only these few months to really get into it. I've been thinking about this non stop and wondering if someone could answer this question.
I understand the usage of this but I am curious to know how this is done.Below in the code on line 19.The parameters are set for a string which then is used to output on the line below that.What I am wondering is why are the parameters needed and you are not able to just use the string name,Even though mystring is not using the x variable.
#include <iostream>
usingnamespace std;
string mystring = "The number you are looking for does not exists";
int main()
{
try{
int momsAge =67;
int sonsAge = 99;
if(sonsAge>momsAge){
throw mystring ;
}
}catch(string x ){
cout<< mystring << endl;
}
}
In this case parameters are not needed. However it is not a good style even here: you should receive reference to exception, not the copy.
As poteto said, if your code would be something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string> //Do not use std::string without this header
usingnamespace std;
int main()
{
try{
string mystring = "The number you are looking for does not exists";
int momsAge =67;
int sonsAge = 99;
if(sonsAge>momsAge)
throw mystring ;
} catch(string& x ){
cout<< mystring << endl;
}
}
It would not work, and you will have to use parameter x.