Jimmyt1988
Jimmyt1988

Reputation: 21126

If a function expects a return value, but inside the function i catch an error and want to break out

If a function expects a return value, but inside the function i catch an error and want to break out of that function, how do I do this in C#... My issue is this (feel free to skip to the commented lines):

    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;
        }
    }

Upvotes: 1

Views: 73

Answers (3)

Ryan Peters
Ryan Peters

Reputation: 7708

Your calling code should be handling the exceptions. If your execution cannot continue, let the exception bubble up and remove some of the unnecessary try/catch in your method here.

Upvotes: 0

Gerhard Powell
Gerhard Powell

Reputation: 6175

Put throw() at the end of your catch() statement. Then it will handle it, but throw the same exception again to bubble up.

Upvotes: 0

Simon Whitehead
Simon Whitehead

Reputation: 65079

Don't catch the exception.

Leave the exception to be caught by the caller - or, optionally catch it and wrap it in your own Exception type.

You're putting all of your eggs in one basket here - catching it so far down leaves you little wiggle room. Letting it bubble up gives you more options for handling it.

Upvotes: 3

Related Questions