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.
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.
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.
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.
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.
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:)