c# - 不是所有的代码路径都通过 C# 编译器返回值

标签 c# string exception compilation

这是一个基本的字符串反向程序,我想在其中进行某种程度的异常处理。但是在编译过程中它给了我一个错误“并非所有代码路径都返回值。我无法找出原因

 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;


        }

最佳答案

如果发生异常,则没有 return 语句被执行。走一遍。

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

关于c# - 不是所有的代码路径都通过 C# 编译器返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1148218/

相关文章:

c# - 如何在 UWP 应用程序中创建文件夹?

javascript - split() js 最后一个数组项

java - getRichStringCellValue().getString() 和 getRichStringCellValue().toString() 有什么区别

c# - 注册表监控,包括内核模式注册表访问?

c# - 抛出异常有什么意义?

c# - 服务无法启动,但确实启动了?

arrays - JNI设置静态字段字符串数组

php - 放置异常后 html 表单不起作用

exception - 错误: Current Displayable is an Alert

c++ - 异常在构造函数 try block 中被捕获并处理,但仍会再次被重新抛出