C#从try-catch块返回

Yuk*_*uya 3 c# return try-catch

为什么我不能从try块中返回我从url获得的图像?对不起英语不好:(.

这是我得到的错误:

退货声明丢失

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

        }
    }
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激,因为我现在卡住了:(.

Ode*_*ded 7

您需要从所有可能的执行路径返回.

所以,如果你try失败了,你需要从catch函数的末尾返回一些东西.

注意:

你真的不应该有空catch块 - 吞咽异常是一个非常糟糕的习惯,它可以调试并找到异常起源的地方.

我会把函数写成:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果你有在一些catch区块,无论是(抛出该异常高达throw;)登陆之后,或返回null.