how to insert try/catch throw

I have this code I wrote with some data and what I'm supposed to do is insert exception handling into the code. The problem is I've seen the basic examples of it. But I don't know how to implement it into my code. Any guidance would be of help.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main(){
	string filename, n;
	cout << "To find a file, type in the file name. " <<endl;
	cin >> filename;
	ifstream fin(filename.c_str());
	while (!fin){
		cout << "Error! Enter a new filename. " << endl;
		cin >> filename;
		fin.open(filename.c_str());
	}
	while (getline(fin, n)){
		cout << n  << endl;
	}

	fin.close();
	return 0;
}	


And the file is:
1
2
3
4
5
6
7
8
9
10
A
F
D
E
U
B
V
X
M
V
You can put the code in the main function in a try block and use the exception type catch block to get general type exceptions. You can also use the default catch block(catch(...)). For special catching, you can read the documentation of the classes(eg: std::string) you use, and check the type of exceptions the throw.

For more info: http://cplusplus.com/doc/tutorial/exceptions/

HTH,
Aceix.
I checked it out. So I'm trying it with my program. So far I can't get it. This is what i got so far. Obviously it's wrong and doesn't work but I have to play around with it. Any suggestions would be good.
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
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main(){
    ifstream fin;
	string filename, n;
    try{
        cout << "To find a file, type in the file name. " <<endl;
        cin >> filename;
        ifstream fin(filename.c_str());}
	catch (string filename){
		cout << "Error! Enter a new filename. " << endl;
		cin >> filename;
		fin.open(filename.c_str());
	}
	try {
        getline(fin, n);
    }
    catch (string n){
        cout << n << endl;
	}
	fin.close();
	return 0;
}
I'm still stuck. Anything?
Don't use exceptions as you would use return codes.

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
29
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main(){
  try{
//normal flow
	string filename, n;
	cout << "To find a file, type in the file name. " <<endl;
	cin >> filename;
	ifstream fin(filename.c_str());
	while (!fin){
		cout << "Error! Enter a new filename. " << endl;
		cin >> filename;
		fin.open(filename.c_str());
	}
	while (getline(fin, n)){
		cout << n  << endl;
	}

	fin.close();
  }
  catch(...){ 
//error handling
    std::cerr << "something went wrong\n";
  }
	return 0;
}
Now, ¿what part of your code may throw an exception?
Thanks! I'm understanding it a little more. I have been playing around with throws and my guess is that the throw should be for:
ifstream fin(filename.c_str()); in line 12 or this
cout << "Error! Enter a new filename. " << endl; in line 14.
I could be wrong since implementing them didn't exactly work. If it was line 12 then I get an error about unexpected type name and if it's line 14 then after I run the code, it ends after the first error. Like I said I could be wrong.
Simple example with throw:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
try{
  int j=0;
  cout<<"Enter 2: ";
  cin>>j;
  if(j!=2)
    throw 1;
}
catch(int errCode){
  if(errCode==1)
    cerr<<"\nYou did not enter 2!";
}
catch(...){
  cerr<<"Oops, an unexpected error";
}


HTH,
Aceix.
Thanks, but unfortunately I've seen dozens of the simple examples. My problem is that I have to apply it to my specific code. I understand the concept now, I just don't know how to apply it to my code. I have understood what ne555 said about not using the try/catch as a return type statement. But the throw is confusing me. I don't know where to put it into my code if at all.
I was also reading that people shouldn't use catch(...). It was called 'dangerous' in big amounts of code but I guess for my example it won't matter.
> I don't know where to put it into my code if at all.
¿what errors do you want to handle as exceptions?
You may setup the stream to throw the exception automagically http://www.cplusplus.com/reference/ios/ios/exceptions/
Ok I get it. So what I did was I took a slightly altered version of the program and inserted a throw exception that if you tried entering a filename more than 3 times then the an exception is thrown that says to stop trying to hack.
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
29
30
31
32
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main(){
    try {
        string filename, n;
        int count = 0;
        cout << "To find a file, type in the file name. " <<endl;
        cin >> filename;
        ifstream fin(filename.c_str());
        count++;
        while (!fin){
            count++;
            cout <<  "Error! Enter a new filename!" ;
            cin >> filename;
            fin.open(filename.c_str());
            if (count ==3)
                throw count;
            
        }
        while (getline(fin, n)){
            cout << n  << endl;
        } 
        fin.close();
        }
         catch (...) {
             cerr << "Stop trying to hack!" << endl;
          }
	return 0;
}


Thanks for all the help!
Last edited on
Assuming you want the same basic functionality where the only "error" situation is the user entering the name of a file that doesn't exist, one must rearrange the code a bit, and you may end up with a construct similar to this one (though I would suggest using std::runtime_error in your situation:)

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>
#include <string>
#include <stdexcept>

int main()
{
    bool successful = false ;

    while ( !successful )
    {
        try {
            std::cout << "Enter a number between 0 and 100: " ;
            int value ;
            std::cin >> value ;

            if ( value < 0 || value > 100 )
                throw std::out_of_range("number is out of range") ;

            std::cout << "You entered " << value << '\n' ;
            successful = true ;
        }

        catch( std::exception& ex )
        {
            std::cout << "ERROR: " << ex.what() << '\n' ;
        }
    }
}	

Topic archived. No new replies allowed.