【问题标题】:C# Return from a try-catch blockC# 从 try-catch 块返回
【发布时间】:2012-05-18 06:20:03
【问题描述】:

为什么我不能从 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)
        {

        }
    }

任何帮助将不胜感激,因为我现在陷入困境:(。

【问题讨论】:

    标签: c# return try-catch


    【解决方案1】:

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

    因此,如果您的 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;
    }
    

    如果您确实catch 块中有内容,请在记录异常后抛出异常 (throw;),或者返回 null

    【讨论】:

      【解决方案2】:

      如果接受图片加载失败时返回null,你可以:

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

      否则,当异常被捕获时该方法应该返回什么? 另外,您永远不应该像上面那样隐藏异常,这是一种非常糟糕的做法。

      【讨论】:

      • 如果捕获到异常,我想显示资源中的图像。我这可能吗?
      • 当然,将图片嵌入为嵌入式资源,看看这里:stackoverflow.com/questions/1192054/…
      • 谢谢,我试试看:)。
      • 您仍然有吞下顶级异常的问题。这是邪恶的,这个答案并没有指出这是危险的!
      【解决方案3】:

      您可以从 try 块中返回一个对象。您必须确保所有执行路径都返回该对象。

      如果我们在 try 块中获得图像:

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

      如果在调用 GetImageFromDb() 期间引发异常,则将控制传递给 catch 块。这意味着我们跳过了 return 语句。当控制权返回给调用者时,调用者期望返回值。

      var callerVariable = GetPicture();
      

      现在我们需要从 catch 传回一个值来执行赋值。因为我们正在处理引用类型,所以我们可以返回 null(假设 null 是有效的执行状态)。将捕获更新为

      catch(Exception ex)
      {
        return null;
      }
      

      【讨论】:

        【解决方案4】:

        你需要一个return语句来处理你退出try时的情况,因为抛出了一个异常。

        所有代码路径都必须有一个返回,而您有一个没有。即进入try块,抛出异常,然后在catch中吞下。离开后,你没有回报。

        顺便说一句,吞噬顶级Exception 类型是邪恶的。不要这样做。

        【讨论】:

        • 但如果我这样做,Visual Studio 会告诉我:“无法解析符号 'img'。
        • @Darkshadw:嗯,这是一个不同的问题。 imgtry 的本地地址,因此您当然不能在 try 之外访问它。我不能告诉你什么适合你的场景。考虑消除异常吞咽,如果您不想这样做,请使用return null
        • 除了使用 return null 我还可以告诉他类似:return Properties.Resources.defaultimage.png?
        • @Darkshadw:是的。你只需要返回一些东西。
        【解决方案5】:

        因为如果出现异常,则不会返回任何内容。要么你的 catch 返回 null,要么完整的方法应该返回 null。

        您可以使用以下两个返回语句之一。

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

        【讨论】:

          【解决方案6】:

          您的“catch”块中没有返回语句。

          如果img.Save 抛出异常,您将输入catch,然后离开catch,并且永远不会遇到return。例如:

          public static Image GetExternalImg(string name, string size)
          {
              try
              {
                  // Code here
                  return img;
              }
              catch (Exception)
              {
                  return null;
              }
          }
          

          【讨论】:

            【解决方案7】:

            函数在所有可能的代码路径上都必须有一个return。这里的一个可能的代码路径是try 块的主体抛出一个异常,该异常在catch 块中处理。包含catch 块的代码路径没有返回语句,因此是非法的。

            catch 块中,必须有returnthrow 语句

            【讨论】:

              【解决方案8】:

              来吧:

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

              【讨论】:

                【解决方案9】:

                在您的情况下,您不能保证会返回图片。这就是为什么你需要返回一些东西或者重新抛出异常。

                【讨论】:

                  猜你喜欢
                  • 2015-07-07
                  • 2016-02-01
                  • 2016-05-06
                  • 2016-03-28
                  • 2017-06-17
                  • 2015-10-24
                  • 1970-01-01
                  • 2019-08-31
                  • 2014-04-30
                  相关资源
                  最近更新 更多