Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Return from a try-catch block

I why can't I return the image I get from the url from within a try block? Sorry for the bad English :(.

This is the error I get:

Return statement is missing

    public static Image GetExternalImg(string name, string size)
    {
        try
        {
            // Get the image from the web.
            WebRequest req = WebRequest.Create(String.Format("http://www.picturesite.com/picture.png", name, size));
            // Read the image that we get in a stream.
            Stream stream = req.GetResponse().GetResponseStream();
            // Save the image from the stream that we are rreading.
            Image img = Image.FromStream(stream);
            // Save the image to local storage.
            img.Save(Environment.CurrentDirectory + "\\images\\" + name + ".png");
            return img;
        }
        catch (Exception)
        {

        }
    }

Any help would be appreciated, because I'm stuck right now :(.

like image 435
Yuki Kutsuya Avatar asked Sep 06 '25 17:09

Yuki Kutsuya


1 Answers

You need to return from all possible execution paths.

So, if your try fails, you need to return something from either the catch or the end of the function.

Note:

You really shouldn't have empty catch blocks - swallowing exceptions is a really bad habit which make debugging and finding where an exception originated from really difficult.

I would write the function as:

public static Image GetExternalImg(string name, string size)
{
    // Get the image from the web.
    WebRequest req = WebRequest.Create(String.Format("http://www.picturesite.com/picture.png", name, size));
    // Read the image that we get in a stream.
    Stream stream = req.GetResponse().GetResponseStream();
    // Save the image from the stream that we are rreading.
    Image img = Image.FromStream(stream);
    // Save the image to local storage.
    img.Save(Environment.CurrentDirectory + "\\images\\" + name + ".png");
    return img;
}

If you do have something in the catch block, either throw the exception up (throw;) after logging it, or return null.

like image 88
Oded Avatar answered Sep 09 '25 06:09

Oded