return 放在exception的什么地方?
用C#很长时间了,刚刚开始注意的问题。
private static MyClass TestA()
{
MyClass myClass = "TestA";
try
{
throw new Exception();
}
catch
{
}
return MyClass;
}
// TestA没有问题
private static string TestB()
{
try
{
string str = "TestB";
//throw new Exception();
return str;
}
catch
{
}
}
// TestB编译不通过 错误信息 并非所有的代码
private static string TestC()
{
try
{
string str = "TestC";
//throw new Exception();
return str;
}
catch( Exception ex )
{
throw ex;
}
}
//TestC编译通过
问题点数:100、回复次数:8Top
1 楼IntelliSense(Sense)回复于 2006-03-08 09:06:55 得分 5
catch
{
return null;
}Top
2 楼wf5360308(冷月孤峰)回复于 2006-03-08 09:08:56 得分 10
private static string TestB()
{
try
{
string str = "TestB";
//throw new Exception();
}
catch
{
return Err_str;
}
return str;
}Top
3 楼BlueMountain_1980(蓝色山峰)回复于 2006-03-08 09:10:41 得分 0
private static string TestB()
{
try
{
string str = "TestB";
//throw new Exception();
return str;
}
catch
{
return null;
}
}
//IntelliSense(Sense) 也就是说当执行到catch的时候就没有return 所以编译器才报错??Top
4 楼dingzhaofeng(Alading)回复于 2006-03-08 09:18:01 得分 5
异常中ingTop
5 楼lovvver(ElephantTalk.Bright)回复于 2006-03-08 09:18:14 得分 10
看你的要求了,如果出现异常,抛出,而不返回的话,
private static string TestB()
{
try
{
string str = "TestB";
...
}
catch(Exception ex)
{
throw ex;
}
return str;
}
如果你想出现异常则返回null的话:
private static string TestB()
{
try
{
string str = "TestB";
//throw new Exception();
....
}
catch
{
return null;
}
return str;
}Top
6 楼Ivony(授人以鱼不如授人以渔,上海谋生)回复于 2006-03-08 09:41:32 得分 10
应该是这样的吧:
private static string TestB()
{
try
{
string str = "TestB";
throw new Exception(); //因为这里抛出异常,被下面的catch捕获,下面的代码跳过
return str;//这里应该有个警告,检测到无法访问的代码
}
catch//这里捕获了异常后,没有返回值,也没有再抛出异常,所以报错。
{
}
}Top
7 楼yuanarea(Sail before)回复于 2006-03-08 10:10:48 得分 10
private static string TestB()
{
try
{
string str = "TestB";
//throw new Exception();
return str;
}
catch{
//错误处理
}
finally
{
return null;
}
}Top
8 楼sogno(一觞一咏)回复于 2006-03-08 10:36:51 得分 50
返回和抛出异常都是方法的出口点,区别只是前者是正常出口点,后者是异常出口点。
Not all code paths return a value意味着方法中至少有一条路径不包括这样的出口点,而try{} catch{}就是一种分支路径Top




