George
George

Reputation: 337

C++ Exception Not being caught

Im attempting to throw an EmptyListException when my linked list is empty, but the program keeps terminating if i uncomment the throw EmptyListException(). this is my EmptyListException header

#ifndef EMPTYLISTEXCEPTION_H
#define EMPTYLISTEXCEPTION_H

#include <stdexcept>
using std::out_of_range;
class EmptyListException : public out_of_range
{
    public:
        EmptyListException(): out_of_range("Empty List!\n") {}

};

#endif // EMPTYLISTEXCEPTION_H

-- Throw command in Clist.h

template <typename E>
E Clist<E>::Remove() throw()
{
    if(isEmpty())
    {
        cout << "Empty List, no removal";
        //throw EmptyListException();
        return '.';
    }
        ... code
}

-- catch in Main

try{
    cout << list->Remove() << endl;
} catch(EmptyListException &emptyList)
{
    cout << "Caught :";
    cout << emptyList.what() << endl;
}

The error 'This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

Upvotes: 1

Views: 3348

Answers (3)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

Well, you told the compiler that you will not throw any exceptions from your Remove()! When you violate this promise it terminates the program. Get rid of throw() in the function declaration and try again.

Upvotes: 5

Matthieu M.
Matthieu M.

Reputation: 299730

The problem is that the throw specifier is... special.

Normally, it is suppose to be used to precise the list of exceptions that the function might return (with inheritance working as usual):

void func() throw(Ex1, Ex2, std::bad_alloc);

When used without an empty exception list, it therefore indicates that this method will never throw. Should it throw, then the runtime will call std::terminate immediately, which by default will just terminate the program.

In general, you should not use exceptions specifications.

Note: C++11 introduced the noexcept keyword to indicate that a function never throws, it's much more intuitive...

Upvotes: 1

Tom W
Tom W

Reputation: 1334

That throw() in the signature of your Remove function is a promise to the compiler that you will not be throwing anything in that function. You need to remove that if you're going to throw anything from inside.

Upvotes: 3

Related Questions