简体   繁体   English

C ++异常未捕获

[英]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(). 我试图在我的链表为空时抛出EmptyListException,但如果我取消对throwEmptyListException()的注释,程序将继续终止。 this is my EmptyListException header 这是我的EmptyListException头

#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 -在Clist.h中抛出命令

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

-- catch in Main -赶上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() ! 好吧,您告诉编译器,您不会从Remove()引发任何异常! When you violate this promise it terminates the program. 当您违反此承诺时,它将终止程序。 Get rid of throw() in the function declaration and try again. 摆脱函数声明中的throw() ,然后重试。

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. Remove函数签名中的throw()是对编译器的承诺,即您不会在该函数中抛出任何内容。 You need to remove that if you're going to throw anything from inside. 如果要从内部扔东西,则需要删除它。

The problem is that the throw specifier is... special. 问题在于throw说明符非常特殊。

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. 如果抛出该异常,则运行时将立即调用std::terminate ,默认情况下它将仅终止程序。

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... 注意:C ++ 11引入了noexcept关键字,以指示函数永不抛出,它更加直观...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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