2013-02-23 93 views
1

我想拋出這樣一個異常:代碼調用終止而不是拋出異常

if (...) { 
    throw "not found"; 
} 

,趕上這樣的:

try { 
    myfunction(); 
} catch (const char * msg) { 
    cout << msg << endl; 
} 

但隨後說

terminate called after throwing an instance of 'char const*' 

爲什麼它要求終止,而不是拋出我的「未找到」?

編輯:

我改成了這樣:

try { 
    throw "not found"; 
} catch (const char * msg) { 
    cout << "test" << endl; 
} catch(...) { 
    cout << "test" << endl; 
} 

,我也得到了同樣的錯誤!

EDIT2: 當我沒有調用上面的特定方法時,它的工作原理!但我不明白這種方法與異常有什麼關係,我沒有在上面提到的myfunction()中使用它。讓我測試更多,然後我會回到你身邊!

編輯3:

哦,我的,這是尷尬的。看起來我稱爲錯誤的功能。我非常抱歉用這種可恥的經歷打擾你!

+2

@ ta.speot.is:什麼不是什麼? – 2013-02-23 23:58:02

+0

@BastianMattes:你能展示你真實的代碼嗎? – 2013-02-24 00:01:14

+0

使用調試器找出 – James 2013-02-24 00:04:01

回答

1

如果在try/catch塊外使用throw,終止會被調用。確保拋出的函數在try塊中。

#include <iostream> 

void myFunc() 
{ 
    throw "Throwing!"; 
} 

int main() 
{ 
    try 
    { 
     myFunc(); 
    } 
    catch(...) 
    { 
     std::cout << "Works fine."; 
    } 

    myFunc(); // Terminate gets called. 

    return 0; 

} 
+0

看到我上面的編輯,我肯定在try塊裏面扔。 – gartenriese 2013-02-26 11:37:11

相關問題