日期:2014-05-18  浏览次数:20719 次

try catch一个有趣的问题。
C# code

        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();
            }
        }


这样的代码不会报错,但是如果是
C# code

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关键子的函数中
系统要求,在任何一个可能的路径上都要有一个return值你的这个函数,在发生异常,进入catch (Exception ex){}中的时候,就没有return了,所以编译器会报错

要想顺利通过编译,你必须在catch (Exception ex){}里面加一个return才符合语法要求

------解决方案--------------------
定义了int你就老老实实地都renture不要去考虑其它的不安全因素了
------解决方案--------------------
拿第一条语句发生异常也没有返回值的啊,为什么啊?
------解决方案--------------------
C# code
using System;
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
            {

            }
        }
    }
}

------解决方案--------------------
没报错 `
------解决方案--------------------
回复内容太短了!。。。

我也想知道原因

------解决方案--------------------
static public int AppendOneFileToAnother()
{
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;
}
最好不要那么写。没有意义的话。
虽然没什么错。


我靠