简体   繁体   中英

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.

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.

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM