2012-07-03 51 views
4

下面C++瑣碎的try-catch原因中止

// g++ centro.cc -o centro 

#include <iostream> 
using namespace std; 

int main(int argc, char *argv[]) 
{ 
    try 
    { 
     cout << "Going to throw" << endl; 
     throw; 
    } 
    catch(...) 
    { 
     cout << "An exception occurred" << endl; 
    } 
    return 0; 
} 

簡單的代碼產生一箇中止:

Going to throw 
terminate called without an active exception 
Aborted (core dumped) 

我不明白什麼是錯的,任何人可以點我在正確的方向?

回答

7

你行

throw; 

是重新拋出異常的catch塊的語法。

你應該寫:

throw std::exception(); 
8

試試看東西。你沒有拋出任何異常。

throw;本身通常用於在catch塊內重新拋出相同的異常。

將結果與throw "something";std::exception的實例進行比較。

2

throw;自身重新拋出當前正在處理的異常,但沒有一個在你的代碼。

你需要拋出一些東西。改爲嘗試像throw std::runtime_error("my message");。您需要爲此包括#include <stdexcept>

在實際的代碼,你需要創建自己的異常類拋出最有可能

3

這是由標準(15.1)規定:

8)拋出表達無操作重新拋出當前處理的 異常(15.3)。該臨時例外現有 重新激活;沒有新的臨時異常對象被創建。 的例外不再被認爲是被捕獲的;因此, std :: uncaught_exception()的值將再次爲true。 9)如果目前沒有 異常處理,則執行不帶操作數的throw-expression 調用std :: terminate()(15.5.1)。