2010-06-24 160 views
9

throw之後的值是否對return有利?如果不是,return語句是否可以省略,並且是否可以刪除編譯器錯誤C4715: not all control paths return a value拋出異常後返回

在此先感謝。

編輯:(示例代碼)

for (ushort i = 0; i < itsNumUnits; ++i) 
    if (unitFormation[i] == unit) 
    { 
     return unitSetup[i]; 
    } 
    else 
     throw unit; 

return 0; 
+2

如果程序中的最後一個語句是'throw',並且您仍然收到警告,那麼您應該發佈代碼示例並說出您正在使用的編譯器。 – 2010-06-24 12:58:38

+0

我想到的是我在問題中添加的那種東西......對不起,之前沒有添加示例。 – 2010-06-24 16:21:48

+0

編譯器警告不是語言或標準的問題,而是編譯器。我假設你從錯誤消息的形式使用某種版本的Visual C++,但它可能有助於知道哪一個。 – 2010-06-24 16:53:19

回答

7

沒有必要異常拋出後返回一個值。如果你有這個錯誤,你應該檢查你的代碼可以得到的路徑而不會拋出異常,例如

if (something) 
    throw Exception; 
else 
    return value; 

未能在「如果」的「其他」分支返回值會導致編譯錯誤,因爲異常可能會或可能不會取決於something值拋出。

+3

MSVC將提供C4715:並非所有控制路徑都會爲代碼中的if路徑返回一個值,即使此路徑始終引發也無法返回。 – Pait 2013-01-29 21:54:39

2

投擲本身終止函數執行。但是如果你的函數返回一個值,並且這個異常不會被拋出,你必須注意返回一個值。例如:

bool foo(bool _flag) throw(...) 
{ 
    if (_flag) 
    { 
     throw "foo is throwing an exception"; 
    } 
    return true; 
} 
-1

後拋出你最終在catch(下面的代碼不執行)。唯一被執行的塊是finally。

如果你想實現的東西像你描述上面去的東西是這樣的:

object returnVal = null; // the bad 
try 
{ 
    //some code here 
    throw new Exception(); // something bad happened 
    //some more code 
    returnVal = new object(); // the good 
} 
catch(Exception ex) 
{ 
    // log, try to recover etc. 
    // maybe it`s a good idea not to throw it away if you can handle it here! 
} 
return returnVal; // either the good or the bad (never the ugly!) 

的C#相當於警告的是一個編譯器錯誤,從而以任何方式,我不認爲是個好主意是擺脫編譯器警告,但試圖解決它們。

問候......

+0

在C++中沒有'finally',問題沒有提及捕獲異常。如果編譯器由於在無條件拋出之後沒有'return'而產生警告,那麼警告就是假的。 – 2010-06-24 13:05:53

+5

非常不好的C++代碼,我們沒有'object','null',或'new'遍佈各處...... – 2010-06-24 13:07:19

+0

它實際上是C#但我認爲它甚至有一個相似的小水平...... – Padel 2010-06-24 13:14:22

0

最接近相當於能夠「迴歸」的值,以及拋出一個例外是當函數拋出異常之前寫入指針或引用的對象:

void my_func(int& ret) 
{ 
    ret = 0; 

    for (ushort i = 0; i < itsNumUnits; ++i) { 
     if (unitFormation[i] == unit) { 
      ret = unitSetup[i]; 
      return; 
     } 
     else { 
      throw unit; 
     } 
    } 
} 

然而,這種模式很容易出錯,很少有用。在使用前請仔細考慮。