C# - 处理异常和STOP执行

时间:2013-04-23 13:58:29

标签: c# exception web service exception-handling

我们说我有两节课。以下是名为 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 个答案:

答案 0 :(得分:3)

您可以在此处使用关键字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关键字。

答案 1 :(得分:2)

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

Environment.Exit(ERROR_INVALID_COMMAND_LINE)

答案 2 :(得分:0)

您可以捕获异常,对其执行某些操作,然后重新抛出异常,以便不会执行此方法的其他代码。

try{
   ...    
}catch(Exception ex){
   // do something with ex
   throw;
}

答案 3 :(得分:0)

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
}