得到错误并非所有的代码路径由C#编译器的返回值 [英] getting error not all code paths return value by c# compiler
本文介绍了得到错误并非所有的代码路径由C#编译器的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个基本的字符串反向计划,我想这样做例外处理它某种程度。但是在编译过程中它给了我一个错误并不是所有的代码路径返回值。我无法找出原因
公共静态字符串反转(字符串s)
{
试
{
如果(string.IsNullOrEmpty(S))
{
抛出新的NullReferenceException();
}
的char [] C = s.ToCharArray();
INT开始= 0;
INT结束= c.Length - 1,
字符温度;
同时(开始<结束)
{
临时= C [开始];
C [开始] = C [结束];
C [完] =温度;
开始++;
end--;
}
返回新的字符串(C);
}
赶上(异常前)
{
Console.WriteLine(ex.Message);
}
}
感谢球员...我更改代码的东西像这样
公共静态字符串反转(字符串s)
{
如果(!string.IsNullOrEmpty( S))
{
的char [] C = s.ToCharArray();
INT开始= 0;
INT结束= c.Length - 1;
炭温度;
同时(开始<结束)
{
临时= C [开始]。
C [开始] = C [结束]
C [结束] =温度;
开始++;
end--;
}
返回新的字符串(C);
}
,否则返回小号;
}
解决方案
如果发生异常则没有被执行return语句。走到底。 p>
最好的补救方法(我的选择)将是删除整个try / catch语句。像反向效用函数不应该处理(自己的)异常。
This is a basic string reverse program and I want to do some level of exception handling in it. But during compilation it gives me an error "NOt all code paths return value. I am not able to find out why
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);
}
}
Thanks guys...I change the code to something like this
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;
}
解决方案
If an exception happens then there is no return statement being executed. Walk it through.
The best remedy (my choice) would be to remove the entire try/catch . A utility function like Reverse should not handle (its own) exceptions.
这篇关于得到错误并非所有的代码路径由C#编译器的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文