簡體   English   中英

C ++異常未捕獲

[英]C++ Exception Not being caught

我試圖在我的鏈表為空時拋出EmptyListException,但如果我取消對throwEmptyListException()的注釋,程序將繼續終止。 這是我的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

-在Clist.h中拋出命令

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

-趕上Main

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

錯誤“此應用程序已請求運行時以異常方式終止它。 請與應用程序的支持團隊聯系以獲取更多信息。

好吧,您告訴編譯器,您不會從Remove()引發任何異常! 當您違反此承諾時,它將終止程序。 擺脫函數聲明中的throw() ,然后重試。

Remove函數簽名中的throw()是對編譯器的承諾,即您不會在該函數中拋出任何內容。 如果要從內部扔東西,則需要刪除它。

問題在於throw說明符非常特殊。

通常,假定它用於精確化函數可能返回的異常列表(繼承照常進行):

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

因此,如果在不使用空異常列表的情況下使用該方法,則表明該方法將永遠不會拋出。 如果拋出該異常,則運行時將立即調用std::terminate ,默認情況下它將僅終止程序。

通常,您不應使用例外規范。

注意:C ++ 11引入了noexcept關鍵字,以指示函數永不拋出,它更加直觀...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM