Thread: try/catch

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    255

    try/catch

    i need a try catch block i presume so if my teacher tests with an empty file or a file that has too many variables to go into it. it doesnt blow up and i am clueless with try/catch/throw blocks.



    Code:
    int load_array(ifstream& in, int file_data[], int arraysize)
    {
        int i = 0;
    in >> file_data[i++];
       while( !in.eof() && i < arraysize)
           in >> file_data[i++];
       return i;
    }
    hooch

  2. #2
    Registered User
    Join Date
    Sep 2005
    Posts
    20
    Code:
    try {
        //if file is empty
              throw "File is empty";
        //read in data from file
        //if too many elemnts
              throw "Too many elements error.";
        //do more stuff
    }
    catch(const * s)
    {
        cout << s << '\n';
        //exit or do whatever you want to do
    }
    very simple example

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    In jcarouth's example:
    Code:
    try{
        throw "File is empty";
    }
    catch(const char * s) // added "char"
    That throws a "char *s". You can also throw other things, like classes, ints, or structs.

    Hey, jcarouth, don't forget your chars.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    ok that makes sense i think but last night when i was looking i couldnt find the specific type of error like

    what do i put to say if(file is empty)

    if(too many elements)

    and what is the const * s in the catch i dont get that???

    not trying to get you to write it for me but for first time ventures it usually helps. though i did try and find the file is empty or too many elements to function to test but couldnt find it when i did look so if someone knows that would be great?
    hooch

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You can check the return value of operator>> first before the while loop to see if the file is empty (if it is false then nothing was read in).

    If i is equal to (or greater than) arraysize when you break out of the while loop and eof() is false, then you have too many elements for the array.

  6. #6
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    ARGH this is confusing

    it still doesnt stop it if it has over 100 it just cuts it off and if it has 0 it crashes not mention i seems to equal 93 for some reason which is way at the beginning of the file

    main:

    Code:
    	bool exit = false;
        double avg;
    	int smallest;
    	int count_abv = 0;
    	int count = 0;
    	int file_data[99];
    	ifstream in("onehundred.dat");
    	while(exit == false)
    	{
    	if(in.is_open())
    	{
    	count = load_array(in, file_data, 99);
    	in.close();
    	if(count == -1)
    		exit = true;
    	else
    	{
        print_array(file_data,count);
    	avg = calc_average(count,file_data);
    	cout << avg << endl;
    	count_abv = count_abv_avg(file_data,count,avg);
    	smallest = smallest_number(file_data,count);
    	display(avg, count_abv);
    	exit = true;

    load_array function

    Code:
    int load_array(ifstream& in, int file_data[], int arraysize)
    {
        int i = 0;
    	in >> file_data[i++];
    	try{
    		if(!file_data[i])
    			throw "File is Empty";
    		while( !in.eof())
                                            in >> file_data[i++];
    		if(i >= arraysize)
    			throw "Too many elements error";
    	}
    	catch(const char* s)
    	{
    		cout << s << endl;
    		i = -1;
    	}
    	cout << "VALUE OF I\n" << i << endl;
       return i;
    }
    hooch

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You don't need exceptions if you are going to catch them in the same function. If you are doing them to learn how to use them then ok, otherwise they aren't very helpful here.

    It's the return value of operator>> that you want to check, not the first value in the function. For example:
    Code:
    if (!(in >> file_data[i++]))
    {
      cout << "File is empty." <<endl;
      return -1;
    }
    You removed the check for the array size from the while loop control. It needs to still be in there to stop the loop if there are too many elements. Then the code that throws the Too many elements exception will work properly.

  8. #8
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    ok well if i dont need a try/catch i wont use it cause i hate it lol cause try catch really looks like a weird if/else that doesnt need to exist same logic as if else. ok well it works fine if its empty but if it has too many elements it just chops it off and computes it accordingly instead of crashing or stopping the program.




    Code:
    int load_array(ifstream& in, int file_data[], int arraysize)
    {
        int i = 0;
    	in >> file_data[i++];
    	
    		if(!(in >> file_data[i]))
    		{
    			cout << "File is Empty\n";
    			i = -1;
    		}   		
      while(in >> file_data[i] && i <= arraysize)
      i++;
      if(i > arraysize)
      {
      i = -1;
      cout << "There are too many elements for this array\n";
      else;
      cout << "VALUE OF I\n" << i << endl;
       return i;
    }
    hooch

  9. #9
    Registered User
    Join Date
    Sep 2005
    Posts
    20
    Quote Originally Posted by dwks
    Hey, jcarouth, don't forget your chars.
    Haha, yeah that's what I get for not checking my work. The forum compiler didn't seem to catch that one.

  10. #10
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    ah i figured it out my files didnt have over 100 for some reason lol oopsie yay it works


    HALLUYA IT WORKS

    i narrowed the problem down....to .net sucks lol after testing it on portable .net and Dev C++ it works fine lol

    it now tells me when it is over array limit when its empty and when its got stuff it calculates
    Last edited by ssjnamek; 09-19-2005 at 09:41 PM.
    hooch

  11. #11
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    so then can if/else do anything that try/catch can?
    hooch

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    No. Not even close. In this case the try catch is unnecessary because you can achieve the same effect. In general, exceptions are very powerful and different from if/else. You can throw an exception and not catch it immediately. Code much further up the chain of functions can catch it later on, and you don't have to clutter the code in between with extra error handling.

    Keep studying up on exceptions and you'll understand. Just know that in the case of throwing the exception and catching it in the same function, it is an unnecessary use and an if statement is probably better.

  13. #13
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    so try/catch is for fatal errors? aka entering a character in an integer input slot? or something else equally as fatal? i guess i can see that making more sense vs some strange if/else spin off that it appears to be by logic means anyway.

    but yes if thats the case im sure ill start studying it some more later mainly the syntax that seems to be irritating.
    hooch

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Implementing try/catch as Macros
    By chacham15 in forum C Programming
    Replies: 18
    Last Post: 09-06-2008, 06:18 PM
  2. Is there a catch to return in a try/catch box?
    By meili100 in forum C++ Programming
    Replies: 25
    Last Post: 11-21-2007, 01:33 PM
  3. Exception Handling, How? Try/Catch throw...
    By chadsxe in forum C++ Programming
    Replies: 16
    Last Post: 07-19-2005, 07:57 PM
  4. try/catch/throw exceptions
    By smd in forum C++ Programming
    Replies: 3
    Last Post: 07-02-2002, 08:44 AM
  5. Try/Catch-What's Wrong
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 12-04-2001, 09:22 PM