2014-09-30 107 views
0

當我使用try catch exception有這一段代碼,我得到以下錯誤:嘗試捕捉異常錯誤

"not all code paths return values"

我的代碼:

public System.Drawing.Image Scan() 
    { 
     try 
     { 

      const string formatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"; 
      WIA.CommonDialog scanDialog = new WIA.CommonDialog(); 
      WIA.ImageFile imageFile = null; 
      imageFile = scanDialog.ShowAcquireImage(WIA.WiaDeviceType.ScannerDeviceType, WIA.WiaImageIntent.GrayscaleIntent, 

      WIA.WiaImageBias.MinimizeSize, formatJPEG, false, true, false); 
      WIA.Vector vector = imageFile.FileData; 
      System.Drawing.Image i = System.Drawing.Image.FromStream(new System.IO.MemoryStream((byte[])vector.get_BinaryData())); 

      return i; 

     } 
     catch (COMException ce) 
     { 
      if ((uint)ce.ErrorCode == 0x800A03EC) 
      { 
       return ce; 

      } 
     } 
+3

因爲你的功能不明確返回值。 'if((uint)ce.ErrorCode == 0x800A03EC)'如果這不是真的,那麼你的catch塊不會返回... – 2014-09-30 16:08:15

+0

[不是所有的代碼路徑都返回一個值]的可能重複(http:// stackoverflow .com/questions/4292067/not-all-code-paths-return-a-value) – 2014-09-30 16:11:57

回答

4

更改catch塊像下面將工作,但仍你面臨一些問題。因爲您的方法返回類型Image,並且您在catch塊中返回COMException。我建議你拋出異常或登錄catch塊

if ((uint)ce.ErrorCode == 0x800A03EC) 
{ 
    //DO LOGGING; 
} 
else 
{ 
    throw ce; 
} 
+1

只需調用'throw'(不含ce)即可。如果您包含ce,您可能會丟失一些堆棧跟蹤信息。 – 2014-09-30 19:29:49

1

這裏有兩個不同的問題。首先,如果條件不符合,你的catch塊不會返回任何東西。其次,catch塊內的返回類型與try塊內的返回類型不同。

你可能想要更多的東西像這樣在你的catch塊:

catch (COMException ce) 
{ 
    if ((uint)ce.ErrorCode == 0x800A03EC) 
     return null; // Don't return anything if a specific code was found 

    throw ce;   // Rethrow the exception for all other issues. 
} 
+0

從HRESULT獲取異常:0x80210015 – 2014-09-30 16:41:21

+0

最好只調用'throw'而不是'throw ce',以免丟失任何堆棧跟蹤信息。 – 2014-09-30 19:30:32