加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

获取错误并非所有代码路径都通过c#编译器返回值

发布时间:2020-12-15 19:30:56 所属栏目:百科 来源:网络整理
导读:这是一个基本的字符串反向程序,我想在其中进行一定程度的异常处理.但是在编译期间它给了我一个错误“NOt所有代码路径返回值.我无法找出原因 public static string Reverse(string s) { try { if (string.IsNullOrEmpty(s)) { throw new NullReferenceExcepti
这是一个基本的字符串反向程序,我想在其中进行一定程度的异常处理.但是在编译期间它给了我一个错误“NOt所有代码路径返回值.我无法找出原因

public static string Reverse(string s)
        {
            try
            {
                if (string.IsNullOrEmpty(s))
                {
                    throw new NullReferenceException();
                }

                char[] c = s.ToCharArray();
                int start = 0;
                int end = c.Length - 1;
                char temp;

                while (start < end)
                {
                    temp = c[start];
                    c[start] = c[end];
                    c[end] = temp;
                    start++;
                    end--;
                }
                return new string(c);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

谢谢你们……我把代码改成了这样的东西

public static string Reverse(string s)
        {
            if (!string.IsNullOrEmpty(s))
            {
                char[] c = s.ToCharArray();
                int start = 0;
                int end = c.Length - 1;
                char temp;

                while (start < end)
                {
                    temp = c[start];
                    c[start] = c[end];
                    c[end] = temp;
                    start++;
                    end--;
                }
                return new string(c);
            }
            else return s;


        }

解决方法

如果发生异常,则不执行返回语句.走过去.

最好的补救措施(我的选择)是删除整个try / catch.像Reverse这样的实用程序函数不应该处理(它自己的)异常.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读