2017-08-29 37 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