Ren
Ren

Reputation: 4680

Method with try catch and exception throws

So I have the following method:

template <class DT> //needs testing
DT& LinkedSortedArrays<DT>::find (const DT& key)
{
    list<SortedArray<DT>>::iterator it = SAList.begin();
    for( ; it != SAList.end(); ++it){
        try{
            if (it == SAList.begin() && key < (*it)[0]) throw Exception();
            return (*it).find(const_cast<DT&> (key));
        } catch (ArrayException e) {

        }
    }
    throw Exception();
}

I have previously defined the classes Exception and ArrayException. (*it).find(const_cast<DT&> (key)) will throw a ArrayException everytime that key is not found in the specific Array class being searched at the moment. SAList is a STL List. The code compiles just fine. However I haven't tried it in my program. Why? I need somebody to confirm or correct me on the following assumptions I have done:

  1. Whenever if (it == SAList.begin() && key < (*it)[0]) throw Exception(); throws an exception, it means it will throw it outside the for loop and even outside the method, right?
  2. I am almost sure that the last line throw Exception(); will throw the Exception outside the method.
  3. The way the for loop is arranged, it won't skip the first element of SAList, right? I mean, I have seen this specific code all over the internet that serves to iterate through all elements of the list as if it was standard or flawless, but... that ++it is twisting my brain. Help?
  4. I was receiving an error of can't convert const int to int& (since the find() in (*it).find(const_cast<DT&> (key)) is not the one belonging to LinkedSortedArrays but rather a different one that requires a DT& variable and LinkedSortedArrays's find() has parameters of type const DT&) and I found that a possible solution might be writing it as const_cast<DT&> (key). I need a second opinion on this.

Lastly, I understand if this is not a specific question and therefore I get downvotes and/or the question gets closed. I simply don't really know where else to ask. If it is the case that I am asking in the wrong place. My apologies.

Upvotes: 0

Views: 145

Answers (1)

Seth Carnegie
Seth Carnegie

Reputation: 75150

  1. Yes, it will go up the stack until it finds the appropriate catch handler. If it finds no such handler, the program will terminate.

  2. Yes it will.

  3. No, it will not, since end should return an iterator to one past the end, not the last element. Unless that container is badly designed as well, but you'll have to consult the documentation to be sure.

  4. That's a bad design, find should take its parameter by const reference. Since you can't, you'll have to make a copy unless you want to risk undefined behaviour:

    DT nonconstkey = key;
    return it->find(nonconstkey);
    

Upvotes: 2

Related Questions