1

假设我有两个班级。这是第一类称为Internet的相关代码:

public void doRequest()
{
     string URL = "http://localhost:4000/HomePage.aspx";
     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
     request.Method = "POST";
     request.ContentType = "application/x-www-form-urlencoded";
     request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}

public void GetRequestStreamCallback(IAsyncResult callbackResult)
{
     HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
     Stream postStream = myRequest.EndGetRequestStream(callbackResult);
     byte[] byteArray = Encoding.UTF8.GetBytes("Test Message");
     postStream.Write(byteArray, 0, byteArray.Length);
     postStream.Close();
     myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}

public void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
     HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
     HttpWebResponse response = null;
     try
     {
          response = (HttpWebResponse)request.EndGetResponse(callbackResult);
          StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream());
          string result = httpWebStreamReader.ReadToEnd();
      }
      catch (WebException)
      {
          Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show("Error: Could not reach the web service"));
      }
}

此代码由名为 MainPage.xaml.cs 的类调用:

private void Button_LogIn_Click(object sender, RoutedEventArgs e)
{
     Internet net = new Internet();
     bool check = net.checkInternet();
     if (check.Equals(false))
     {
     }
     else
     {
         net.doRequest();
         ClientServiceSoapClient web_service = new ClientServiceSoapClient();
         web_service.LogInCompleted += new System.EventHandler<LogInCompletedEventArgs>(LogInComplete);
         web_service.LogInAsync(TextBox_Username.Text, TextBox_Password.Password);
      }
}

我想要的是,如果在doRequest方法调用中发生异常,则处理异常(Internet类末尾的WebException),然后停止执行其后的代码(ClientServiceSoapClient web_service ....)。

我怎样才能做到这一点?

4

4 回答 4

6

您可以在此处使用关键字return(将返回 void)。我实际上已经使用了两次,你有一个空的 if 语句,所以我重新调整了一点。

        private void Button_LogIn_Click(object sender, RoutedEventArgs e)
        {
            Internet net = new Internet();
            bool check = net.checkInternet(); 

            if (check.Equals(false))
                  return;

                try
                {
                    await net.doRequest(); //UPDATED THIS LINE
                    ClientServiceSoapClient web_service = new ClientServiceSoapClient();
                    web_service.LogInCompleted += new System.EventHandler<LogInCompletedEventArgs>(LogInComplete);
                    web_service.LogInAsync(TextBox_Username.Text, TextBox_Password.Password);
                }
                catch
                {
                    //do not throw an error, instead just use the return keyword!
                    return;
                }   
        }

但是,您使用的异步方法对我来说没有意义!如果您需要在继续之前验证结果,则不应异步调用它,它应该串行完成。或者,查看await关键字。

于 2013-04-23T13:59:50.253 回答
2

标题要求停止执行并且不从函数返回。因此,如果您不在 main 函数中,并且您不想抛出异常然后在 main 中再次捕获它,您可以使用 Environment.Exit() 和退出代码.. https://msdn.microsoft。 com/en-us/library/ms681382(v=vs.85)

Environment.Exit(ERROR_INVALID_COMMAND_LINE)
于 2017-06-16T19:46:10.343 回答
1
try
{
    net.doRequest();
}
catch(Exception e)
{
    if(e is WebException)
    {
        //handle appropriately
        return; //will exit the method
    }
    else
        throw; //good idea to throw unexpected exceptions anyway
}
于 2013-04-23T14:06:32.580 回答
1

您可以捕获异常,对其进行处理,然后重新抛出它,这样该方法中的其他代码就不会被执行。

try{
   ...    
}catch(Exception ex){
   // do something with ex
   throw;
}
于 2013-04-23T14:01:12.753 回答