Question about parameter variables

Hello Everyone,

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.

Thank you!



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

using namespace 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;
  }





}
The parameters are not needed. You can use (...), all exceptions will output the same. If mystring was inside try's scope, you would need to use x.
Last edited on
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
using namespace 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.
Topic archived. No new replies allowed.