C++ List Insert Function: Out of Range Errors

  • C/C++
  • Thread starter Defennder
  • Start date
  • Tags
    C++
In summary, the C++ List Insert Function is a built-in function used for inserting new elements into a list data structure. It takes in an index and a value, and throws an out of range error if the index is invalid. This error can be prevented by checking the size of the list before calling the function, or handled gracefully using a try-catch block. There are also alternative functions and data structures available for inserting elements into a list in C++.
  • #1
Defennder
Homework Helper
2,593
5
Code:
void List::insert(int index, const ListItemType& newItem)
[COLOR="Red"]throw(ListIndexOutOfRangeException, ListException)[/COLOR]
{
    int newLength = getLength() + 1;
    if ( (index < 1) || (index > newLength) )
        [COLOR="Blue"]throw ListIndexOutOfRangeException("Bad index in insert");[/COLOR]
    else
    { // try to create new node and place newItem in it
        ListNode *newPtr = new ListNode;
        size = newLength;
        newPtr->item = newItem;

        // attach new node to list
        if (index == 1)
        { // insert new node at beginning of list
            newPtr->next = head;
            head = newPtr;
        }
        else
        { ListNode *prev = find(index-1);
            // insert new node after node
            // to which prev points
            newPtr->next = prev->next;
            prev->next = newPtr;
        } // end if
    } // end insert

The above is from my notes on linked lists. Specifically it is the insert member function of linked list. I see that there are 2 possible things which may be thrown, but in the member function implementation, only one is set up to be thrown in case of out of range error. What of the other?
 
Technology news on Phys.org
  • #2
Maybe it could be thrown by one of the functions called in insert?

Sidenote: from what I've read, exception specifications are really not worth your time (though that might be debatable). Here's a page that outlines some reasons why: http://www.gotw.ca/publications/mill22.htm
 
  • #3
Well looking at the 'insert' function, I see that only getlength() and find(index-1) have been called. But it appears that neither of them has been set up to throw anything at all:

Code:
List::ListNode *List::find(int index) const
{
if ( (index < 1) || (index > getLength()) )
return NULL;
else // count from the beginning of the list.
{
ListNode *cur = head;
for (int skip = 1; skip < index; ++skip)
cur = cur->next;
return cur;
} // end if
} // end find

Code:
int List::getLength() const
{
return size;
} // end getLength
 
  • #4
One more question, I thought the only time we state in the function prototype declaration for eg. "throw (ExceptionOne, ExceptionTwo)" is when both these are set up to be thrown in that member function itself and not in other functions which happen to throw them, but which are called by this member function?
 
  • #5
Well I'm not entirely sure. If you don't catch the exceptions from functions you're invoking in the function, then I think it effectively gets rethrown. And anyways, I tried this on GCC (though not the latest version since I haven't been programming much recently):
Code:
#include <iostream>


class Foo
{
public:
  class FooException{};
  class FooBarException{};

  void Baz() { throw FooException(); }
  void Bar() throw (FooBarException);


};





void My_Unexpected()
{
  std::cerr<<"Unexpected called!";
}

int main()
{
   std::set_unexpected(My_Unexpected);
   Foo f;
   try
   {
   f.Bar();
   }
   catch (Foo::FooException& e)
   {
       std::cerr<<"FooException";
   }
   catch(...)
   {
     std::cerr<<"...";
   }
}
The output was "Unexpected called!" Which makes sense since the compiler will essentially do something like:
Code:
void Foo::Bar()
throw (FooBarException)
{
  try
  {
    Baz();
  }
  catch(FooBarException)
  {
    throw;
  }
  catch(...)
  {
     unexpected();
  }
}

As for your original question, I suppose specifying an exception that isn't thrown isn't necessarily a bad thing. It tells anyone who uses your class what exceptions they need to handle, so in the future if you change your class you can use the "ListException" for something, and if you've already planned for it to throw that exception, it doesn't break existing code that uses insert.

That said, I still don't think exception specification's are a good thing in general.
 
  • #6
What do you mean by "rethrown"? Meaning to say that if you were to write a throw(exception) in the member function implementation, but not set up something in main() to catch it, then what happens?

And I couldn't get your code to compile at all. What is "catch(...)" supposed to contain?

EDIT:I don't like exception handling as well, but my course uses it extensively. So it's best if I familiarise myself with it properly, even if I choose not to use it in practice.
 
Last edited:
  • #7
The second example in my post wasn't meant to be compiled, though it looks compileable to me. catch(...) means catch any exception that isn't already handled (so you get no specific information, only that some unkown exception was thrown)

Just to be clear, I think exceptions themselves are useful, but writing exception specifications (the list of what exceptions a given function will throw) isn't.
 

What is the C++ List Insert Function?

The C++ List Insert Function is a built-in function that allows for inserting new elements into a list data structure in C++. The function takes in an index position and a value, and inserts the value at the specified index. This function is commonly used in data manipulation and algorithmic operations.

How does the C++ List Insert Function handle out of range errors?

When the C++ List Insert Function is called with an index that is out of range, it will throw an out of range error. This indicates that the specified index is invalid and the function cannot insert the value at that position. The program will then exit and an error message will be displayed.

Can out of range errors be prevented when using the C++ List Insert Function?

Yes, out of range errors can be prevented by checking the size of the list before calling the insert function. This can be done by using the size() function, which returns the number of elements in the list. By comparing the desired index with the size of the list, the program can avoid calling the insert function with an invalid index.

What is the best way to handle out of range errors when using the C++ List Insert Function?

The best way to handle out of range errors is to use a try-catch block. This allows the program to catch the out of range error and handle it gracefully, instead of abruptly exiting. Within the catch block, the program can display a custom error message or perform other actions to address the issue.

Are there any alternatives to the C++ List Insert Function for inserting elements into a list?

Yes, there are alternative ways to insert elements into a list in C++. One option is to use the push_back() function, which adds an element to the end of the list. Another option is to use the insert() function, which allows for inserting elements at any position in the list, not just at the end. Additionally, there are other data structures in C++ that can be used for inserting elements, such as vectors and dequeues.

Similar threads

  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
9
Views
2K
  • Programming and Computer Science
Replies
2
Views
1K
Replies
15
Views
4K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
9
Views
2K
  • Programming and Computer Science
Replies
6
Views
12K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
3
Views
8K
Back
Top