try-throw-catch

This is a discussion on try-throw-catch within the C++ Programming forums, part of the General Programming Boards category; For some reason my throws are not handled. Would appreciate your help. main() Code: int main() { displayinfo(); try { ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    49

    try-throw-catch

    For some reason my throws are not handled. Would appreciate your help.

    main()
    Code:
    int main()
    {
    	displayinfo();
    	try
    	{
    		FileHandling operations;
    		operations.ReadFile("data.txt"); //here I have the problem
    		operations.CalculateValues();
    		operations.printdata();
    	}
    	catch (int code)
    	{
    		cerr<<"error code number: "<<NoSuchFile<<endl;
    		exit(1);
    	}
    	return 0;
    }

    The method
    Code:
    void FileHandling::ReadFile(const string& filename) throw(int)
    {
    	int numberOfRows;
    	ifstream infile(filename.c_str());
    	if(infile.fail()) 
    		throw NoSuchFile; //this one is not handled
    	infile>>numberOfRows;//get the number of records in the file
    	if(!numberOfRows)
    		throw numberOfRows;
    	for (int i=0;i<numberOfRows;i++) //cycle through whole file
    	{
    		if(!infile.eof()) //check not eof()
    		{
    			infile.ignore(); //have to ignore \n before getline
    			const int MaxLine = 80;
    			char str[MaxLine];
    			infile.getline(str, MaxLine);
    			if(infile.fail())
    				throw ErrGetLine;
    			if (str[0]!='#') //if line is not comment
    			{
    				numRecords++;
    				double number=atof(str);
    				vec.push_back(number);
    			}//end of if
    		}
    		else
    			throw WrongNumberOfLinesInHeader;
    	}//end of for
    }//getdata
    and the header file, just in case
    Code:
    #ifndef __FILE_HANDLING__
    #define __FILE_HANDLING__
    
    #include <vector>
    #include <iostream>
    using namespace std;
    
    enum ERRORS
    {
    	NoSuchFile,
    	numberOfRows,
    	WrongNumberOfLinesInHeader,
    	ErrGetLine
    };
    
    class FileHandling
    {
    private:
    	double numRecords, sum, average, minimum, maximum;
    	vector<double> vec;
    public:
    	FileHandling();
    	void ReadFile(const string& filename) throw(int);
    	void CalculateValues();
        void printdata() const;
    };
    
    #endif

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
    enum ERRORS
    {
    	NoSuchFile,
    	numberOfRows,
    	WrongNumberOfLinesInHeader,
    	ErrGetLine
    };
    Shouldn't "numberOfRows" be different from your local variable of that name?

    All the other error codes start with upper-case, why not this one [and perhaps call it BadNumberOfRows, and check for negative numers too?]

    Code:
    	catch (int code)
    	{
    		cerr<<"error code number: "<<NoSuchFile<<endl;
    		exit(1);
    	}
    This will print "NoSuchFile" every single time, not the code...

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    49
    You are absolutely right. I fixed what you said. Even though, the catch still doesn't work...

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    The problem is probably that you are throwing something of enum type (ERRORS) but hoping to catch an int. They are not the same type.

    However, it would probably be better to either throw some of the standard exceptions (which are caught by reference) or your own custom error class (derived from std::except) as you can put much more info in them.

    Another thing:
    Code:
    #ifndef __FILE_HANDLING__
    #define __FILE_HANDLING__
    Identifiers beginning with underscores are reserved for compiler implementers. You shouldn't use leading underscores as you may create a conflict with a current or future compiler-specific macro. Better use something like FILENAME_H.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I should have said that I didn't actually think it would fix any real problem [at this point].

    Have you tried stepping through your read function to see if it actually gets to the "throw" part?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,319
    Are you sure that the throw is actually being called? Perhaps put a cout statement in the if block. Did you try throwing a plain int instead of an enum?

    Also, you don't initialize numberOfRows, so if the input fails, it will be some garbage number that is probably not 0, so the if (!numberOfRows) part will probably never be true.

  7. #7
    Registered User
    Join Date
    Dec 2007
    Posts
    49
    Quote Originally Posted by Daved View Post
    Are you sure that the throw is actually being called? Perhaps put a cout statement in the if block. Did you try throwing a plain int instead of an enum?

    Also, you don't initialize numberOfRows, so if the input fails, it will be some garbage number that is probably not 0, so the if (!numberOfRows) part will probably never be true.
    1) I ran it using the debugger and the throw NoSuchFile is called but not handled.
    2) I did if(!numberOfRows) to examine whether there is something different rather than a number in the first line of the file such as a string or char. Won't it work?

  8. #8
    Registered User
    Join Date
    Jan 2005
    Posts
    7,319
    1) So the next step would be to catch the enum type instead of an int.

    2) That won't work because the numberOfRows variable will not be changed if the read fails. This is what you should do:
    Code:
    if (!(infile>>numberOfRows))
    That will evaluate to false if the read fails to read in an integer, and so it will execute the if block and throw your exception. Note that I moved the read into the if control. Don't try to read into numberOfRows twice.

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The point that Daved makes is that the integer value when attempting to read some garbage is not set at all - it is left to be whatever it happened to be.

    And I think the solution to "it's thrown but not caught" is exactly what Anon says: You are throwing an enum, but you are catching an int. Whilst you and I may think that enum and int are the same thing, the compiler doesn't.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    Registered User
    Join Date
    Dec 2007
    Posts
    49
    Quote Originally Posted by anon View Post
    The problem is probably that you are throwing something of enum type (ERRORS) but hoping to catch an int. They are not the same type.
    Solved.
    You're the man! Thank you all!

  11. #11
    Registered User
    Join Date
    Dec 2007
    Posts
    49
    Quote Originally Posted by matsp View Post
    The point that Daved makes is that the integer value when attempting to read some garbage is not set at all - it is left to be whatever it happened to be.
    So how do I verify if the user inserted an int when I ask him to instead of a char for instance?
    I thought the way is

    int num;
    cout<<"insert a num";
    cin>>num;
    if(!num)
    cout<<"you moron, this is not an int";

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    7,319
    >> So how do I verify if the user inserted an int when I ask him to instead of a char for instance?

    I posted while you were posting. Check out my answer in post #8 if you haven't already.

  13. #13
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    Code:
    enum ERRORS
    {
    	NoSuchFile,
    	numberOfRows,
    	WrongNumberOfLinesInHeader,
    	ErrGetLine
    } myerrors ;
    Code:
    	if(infile.fail()) { 
                    myerrors = NoSuchFile ;  
    		throw myerrors ; 
                    }
    Todd

  14. #14
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Todd Burch View Post
    Code:
    enum ERRORS
    {
    	NoSuchFile,
    	numberOfRows,
    	WrongNumberOfLinesInHeader,
    	ErrGetLine
    } myerrors ;
    Code:
    	if(infile.fail()) { 
                    myerrors = NoSuchFile ;  
    		throw myerrors ; 
                    }
    Todd
    That will not help anything, except introduce a global variable, which I'm pretty sure isn't of any use here.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  15. #15
    The larch
    Join Date
    May 2006
    Posts
    3,573
    I don't think globals are necessary.

    Code:
    enum Error {SmallError, BigError };
    ...
    throw BigError;
    ...
    catch (Error err) {
        std::cout << "Error code: " << err << '\n';
    }
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Page 1 of 3 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Exceptions "try, catch, and throw Statements" ???
    By Loic in forum C++ Programming
    Replies: 2
    Last Post: 08-12-2008, 09:22 PM
  2. Throw Catch for External Program
    By dav_mt in forum C++ Programming
    Replies: 6
    Last Post: 04-19-2008, 09:52 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Try...catch...throw or ifs?
    By Kylecito in forum C++ Programming
    Replies: 9
    Last Post: 03-02-2006, 09:41 PM
  5. try catch throw
    By ygfperson in forum C++ Programming
    Replies: 2
    Last Post: 07-27-2003, 02:15 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21