2017-08-29 24 views
0

我創建了一個帶有Web瀏覽器對象的Windows窗體項目。我創建了一個從CSV文件讀入列表的方法。一旦列表填充並且表單加載,列表中的第一項就會出現在網站的文本框中。C#返回語句Try/Catch Not Stopping程序

我使用try/catch塊進行錯誤處理。我注意到如果文件已經打開,它會顯示消息框,但是一旦關閉消息框,代碼就會繼續運行。

它,然後拋出一個參數超出範圍異常時,瀏覽器導航到網頁。

它是正確的,因爲代碼繼續運行。在將瀏覽器導航到網站之前,是否應該添加其他錯誤處理?

預先感謝您。

private void LoadAccounts() 
{ 
     if (!File.Exists(path)) 
     { 
      MessageBox.Show("File Doesn't Exist"); 
     } 

      try 
      { 
       using (StreamReader reader = new StreamReader(path)) 

        while (!reader.EndOfStream) 
       { 
        string line = reader.ReadLine(); 
        string[] accountinfo = line.Split(','); 
        accounts.Add(new WaterAccount(accountinfo[0], accountinfo[1], accountinfo[2],accountinfo[3],string.Empty, string.Empty)); 
       } 

      } 

      catch (IOException ex) 
      { 
       MessageBox.Show(ex.Message); 
       return; 
      } 

} 

編輯以下是代碼塊調用LoadAccounts

public FormWRB() 
{ 
     InitializeComponent(); 
     LoadAccounts(); 
     webBrowserWRB.Navigate("https://secure.phila.gov/WRB/WaterBill/Account/GetAccount.aspx"); 
     buttonExport.Enabled = false; 
} 
+2

你們是不是要停止整個程序?也許嘗試Application.Exit();雖然,它可能更好地通過整個應用程序的正常邏輯來停止程序,但它使其更易於維護。是的,它正確的程序繼續運行,只要有更多的代碼運行後,無論你打電話LoadAccounts() – HumbleWebDev

+0

你可以請張貼調用'LoadAccounts'的代碼?這將使答案更深刻,更緊密地與您的問題相關 –

+0

您可以使'LoadAccounts()'爲'bool'而不是void,然後在您的catch語句中返回false,並相應地處理結果調用LoadAccounts()的代碼塊 – Nova

回答

0

一個try catch語句不會停止運行程序,它只是得到你處理異常的機會。最常見的是記錄異常。 本質上,你的代碼正在做的是試圖運行一段代碼,如果它捕獲到一個IOException然後在消息框中顯示錯誤消息,並且返回只是終止該方法的執行。

這裏是一個可以爲你工作的解決方案。

private void LoadAccounts() 
    { 
     if (!File.Exists(path)) 
     { 
      throw new FileNotFoundException($"{path} does not exist"); 
     } 

     using (StreamReader reader = new StreamReader(path)) 
     { 
      while (!reader.EndOfStream) 
      { 
       string line = reader.ReadLine(); 
       string[] accountinfo = line.Split(','); 
       accounts.Add(new WaterAccount(accountinfo[0], accountinfo[1], accountinfo[2], accountinfo[3], string.Empty, string.Empty)); 
      } 
     } 
    } 

然後在處理LoadAccounts()

try 
    { 
     LoadAccounts(); 
     webBrowserWRB.Navigate("https://secure.phila.gov/WRB/WaterBill/Account/GetAccount.aspx"); 
     buttonExport.Enabled = false; 
    } 
    catch (FileNotFoundException ex) 
    { 
     // Do stuff when file not found here... 
    } 
    catch (IOException ex) 
    { 
     // Handle other exceptions here 
    } 

引用代碼塊: return - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/return try catch - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch