如果一个函数需要一个返回值,但是在函数内部我遇到了一个错误并想退出该函数,我该如何在C#中执行此操作...我的问题是(可以随意跳到注释行):
public static async Task<string> GetData(string url, string props = "")
{
string query = url + "?oauth_token=" + Contract.access_token + props;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(APIURL + query);
request.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.Now.ToString();
request.Method = HttpMethod.Get;
try
{
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
Debug.WriteLine(response.ContentType);
System.IO.Stream responseStream = response.GetResponseStream();
string data;
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
APIError error = new APIError ();
try
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(data)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(APIError ));
error = (APIError )serializer.ReadObject(stream);
}
MessageBox.Show(error.error_description);
return null; // I WANT TO BREAK OUT HERE, I really don't want the application to continue its thread... Is there a way of doing this without having to go and code all my controller model calls to try and catch?
}
catch (Exception e)
{
return data; // The api did not return an error so continue as normal
}
}
catch (Exception ex)
{
var we = ex.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
var code = resp.StatusCode;
MessageBox.Show("RespCallback Exception raised! Message:{0}" + we.Message);
Debug.WriteLine("Status:{0}", we.Status);
return we.Message;
}
else
throw;
}
}
不要抓住例外。
将异常留给调用者捕获-或选择捕获该异常并将其包装为您自己的Exception
类型。
您将所有鸡蛋都放在这里的一个篮子里-抓得太远了,给您留下了很小的摆动空间。让气泡冒出来为您提供了更多处理它的选择。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句