4

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 :(.

Yuki Kutsuya
  • 3,968
  • 11
  • 46
  • 63

9 Answers9

7

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

If it is accepted to return null when the image fail to load you can:

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)
        {
              //grab an image from resource
              return theDefaultImage;
        }
    }

otherwise, what should the method return when the exception is caught ? As an addition, you should never hide the exception as above, it is a really worst practice.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
2

You are able to return an object from a try block. You must ensure that all execution paths return that object.

If we get an image in a try block:

public Image GetPicture()
{
    try
    {
       Image image = GetImageFromDb();
       return image;
    }
    catch(Exception ex)
    {

    }
}

If an exception is thrown during the call to GetImageFromDb() control is passed to the catch block. This mean we skip past the return statement. The caller expects a return value when control is passed back to the caller.

var callerVariable = GetPicture();

Now we need to pass a value back from catch in order to perform the assignment. Because we are dealing with reference types we can return null (assuming null is a valid state of execution). Update the catch to

catch(Exception ex)
{
  return null;
}
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
1

You need a return statement to handle the case when you exit the try because an exception is thrown.

All code paths must have a return, and you have one that doesn't. Namely, enter the try block, throw an exception, and then swallow it in the catch. After you leave the catch, you don't have a return.

By the way, swallowing the top level Exception type is evil. Don't do it.

jason
  • 236,483
  • 35
  • 423
  • 525
  • But if I do that, Visual Studio tells me: "Cannot resolve symbol 'img'. – Yuki Kutsuya May 09 '12 at 17:30
  • @Darkshadw: Well, that's a different problem all together. `img` is local to the `try` so of course you can't access it outside of the `try`. I can't tell you what is right for your scenario. Consider eliminating the exception swallowing, or use `return null` if you don't want to do that. – jason May 09 '12 at 17:31
  • Instead of using return null I can also tell him something like: return Properties.Resources.defaultimage.png? – Yuki Kutsuya May 09 '12 at 17:34
  • @Darkshadw: Yes. You just have to return something. – jason May 09 '12 at 18:31
0

Because if you have an exception, nothing will be returned. Either you catch returns null, or the complete method should return null.

You can use one of the two return statements below.

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)
        {
            //return null;
        }

        //return null;
    }
Dante
  • 3,833
  • 4
  • 38
  • 55
0

You don't have a return statement in your 'catch' block.

If img.Save throws an exception, you'll enter the catch, then leave the catch and never hit a return. For example:

public static Image GetExternalImg(string name, string size)
{
    try
    {
        // Code here
        return img;
    }
    catch (Exception)
    {
        return null;
    }
}
Rob
  • 45,296
  • 24
  • 122
  • 150
0

The function must have a return on all possible code paths. One possible code path here is that the body of the try block throws an exception which is handled in the catch block. The code path which contains the catch block has no return statement and hence is illegal.

From the catch block there must either be a return or a throw statement

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

Here ya go:

  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)
            {

            }
        return null;

        }
blak3r
  • 16,066
  • 16
  • 78
  • 98
0

In your case you are not guaranteed will return image. That's why you need return something or re throw exception.

victor.t
  • 454
  • 4
  • 12