static public int AppendOneFileToAnother()
{
StreamWriter sw = null; StreamReader sr = null;
string tempLineStr = string.Empty;
try
{
return 1;
}
catch (Exception ex)
{
Console.Write("AppendFileErro :" + ex.Message);
logger.Error("AppendFileErro :" + ex.Message);
throw ex;
}
finally
{
sw.Close();
sr.Close();
}
}这样的代码不会报错,但是如果是
static int Main(string[] args)
{
try
{
return 1;
}
catch (Exception ex)
{
Console.Write("AppendFileErro :" + ex.Message);
logger.Error("AppendFileErro :" + ex.Message);
throw ex;
}
finally
{
}就要报错,不是所有路径都返回值。很怪,为啥非main函数中可以没问题?
系统要求,在任何一个可能的路径上都要有一个return值你的这个函数,在发生异常,进入catch (Exception ex){}中的时候,就没有return了,所以编译器会报错要想顺利通过编译,你必须在catch (Exception ex){}里面加一个return才符合语法要求
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
class Program
{
static public int AppendOneFileToAnother()
{
try
{
return 1;
}
catch (Exception ex)
{
Console.Write("AppendFileErro :" + ex.Message);
throw ex;
}
finally
{ }
} static int Main(string[] args)
{
try
{
return 1;
}
catch (Exception ex)
{
Console.Write("AppendFileErro :" + ex.Message);
throw ex;
}
finally
{ }
}
}
}
我这里不报错啊!!Why????????
{
StreamWriter sw = null;
int returnNumber=0;
StreamReader sr = null;
string tempLineStr = string.Empty;
try
{
//todo
}
catch (Exception ex)
{
returnNumber=-1;
Console.Write("AppendFileErro :" + ex.Message);
logger.Error("AppendFileErro :" + ex.Message);
throw ex;
}
finally
{
sw.Close();
sr.Close();
}
return returnNumber;
}
最好不要那么写。没有意义的话。
虽然没什么错。
我靠
我今天又她妈帅了
catch (Exception ex)
{
returnNumber=-1;
Console.Write("AppendFileErro :" + ex.Message);
logger.Error("AppendFileErro :" + ex.Message);
throw ex;
}
这样写即便catch后也不会返回-1啊,直接throw错误出来了。不明白优缺点不过以后还是把returnNumber写在最底下吧。我考,原来你妈妈今天又帅了。