2016-05-13 63 views
-1

我想寫一個方法trycatch其中,我從Web服務獲取數據,並返回數據爲string[]「不是所有的代碼路徑都返回一個值」錯誤BLL

我很努力地返回值。你介意看我的代碼?:

public static string[] UserDetailsWebService(string username, string password) 
{ 
    string[] array = null; 

    using(WebServiceUser.Users use = new WebServiceUser.Users()) 
    { 
     try 
     { 
      WebServiceUser.UserGridList Grid = use.GetUserDetails(username, password, username); 

      array = new string[] { Grid.FirstName, Grid.LastName }; 
     } 
     catch (Exception ex) 
     { 
      if (ex is NullReferenceException || ex is HttpResponseException 
       || ex is WebException || ex is System.Net.Sockets.SocketException) 
      { 
       //throws etc... 
      } 
      else 
      { 
       //throws etc... 
      } 
     } 
     return array; 
    } 
} 

的問題是,我得到這個錯誤:

並非所有的代碼路徑返回一個值。

+0

如果拋出異常,'return'不會被擊中。你還需要'try/catch'之外的'return array'嗎? –

+0

我還會捕獲具有catch-em-all'catch(Exception)'塊的特定異常。這會讓你的代碼更清潔。 –

+0

嘿傢伙,問題不是catch(異常),我只需要返回從web服務取得的數據,這意味着string []數組,我不知何故在那裏做錯了什麼,我不能填充數組並返回它。 – SmackDat

回答

4

請注意,這裏的函數應該返回一個數組string

在功能塊的末尾移動return array;確保我們始終返回某些內容。

public static string[] UserDetailsWebService(string username, string password) 
{ 
    string[] array = null; 

    using (WebServiceUser.Users use = new WebServiceUser.Users()) 
    { 
     try 
     { 
      WebServiceUser.UserGridList Grid = use.GetUserDetails(username, password, username); 

      array = new string[] { Grid.FirstName, Grid.LastName }; 
     } 
     catch (Exception ex) 
     { 
      if (ex is NullReferenceException || ex is HttpResponseException 
       || ex is WebException || ex is System.Net.Sockets.SocketException) 
      { 
       //throws etc... 
      } 
      else 
      { 
       //throws etc... 
      } 
     } 
    } 

    return array; 
} 
+1

這應該如何解決問題?我看到的唯一區別是你把'return'移到''使用' –

+2

之外'我不認爲這是解決方案。 '使用'塊內的「返回」是完全可以接受的,不需要將它移到外面。 –

+0

假設'try'塊中存在錯誤(在您的代碼中)。在這種情況下,沒有任何回報。 –

相關問題