Try…Catch使用小结

 

1.       不要滥用Try…Catch一般来说只在最外层函数上才需要。因为该函数不能将Exception再往外抛了。所以需要Catch住做相应的处理,如显示Error Message。或转化为与调用模块约定好的Error Code。内部函数即使Catch住了Exception,也要往外抛,所以没有必要。

 

2.       为了使用Finally来保证资源的释放。如:

SqlConnection connection = null;

    try

    {

          connection = new SqlConnection(ConnectionString);

          connection.Open();

        

    }

   catch (Exception ex)

    {

         throw ex;

    }

    finally

    {

         if (connection != null && connection.State != ConnectionState.Closed)

         {

              connection.Close();

         }

}

对这种情况Catch住的Exception直接往外抛,不做处理。需要注意的是这里使用Try…Catch不是唯一的办法,也可以使用using语句来保证资源的释放。

 

3.       为了保证函数有统一的出口。比如一个最外层的函数连续调用了一系列内部子函数,当其中某个子函数出错时, 跳到函数最后退出,对这种情况Catch住的Exception直接吃掉,因为在Try里面已经做了错误处理。如:

public Result OutMostFunction()

    {

        Result result = Result.Success;

 

        try

        {

            try

            {

                SubFunction1();

            }

            catch (Exception ex)

            {               

                result = Result.SubFunction_1_Error;              

                throw ex;

            }

 

            try

            {

                SubFunction2();

            }

            catch (Exception ex)

            {

                result = Result.SubFunction_2_Error;

                throw ex;

            }

 

            try

            {

                SubFunction3();

            }

            catch (Exception ex)

            {

                result = Result.SubFunction_3_Error;

                throw ex;

            }

        }

        catch (Exception ex)

        {           

        }

 

        return result;

    }

 

4.       为了区分程序错误与逻辑错误,需要自定义一个Exception类型。比如一个最外层函数调用一个密码验证子函数,就需要区分是因为密码错误(逻辑错误),还是在密码验证过程中程序出现了没有预料到的错误(程序错误)。如:

public class GoOutException : Exception {}

public Result OutMostFunction()

    {

        Result result = Result.Success;

 

        try

        {

            try

            {

                if (!VerifyPassword(password))

                {

                    result = Result.Invalid_Password;

                    throw new GoOutException();

                }

            }

            catch (Exception ex)

            {

                if (!(ex is GoOutException))

                {                   

                    result = Result.General_Error;                   

                }

                throw ex;

            }           

        }

        catch (Exception ex)

        {           

        }

 

         return result;

    }

posted on 2008-11-23 18:34  spacer_robot  阅读(4774)  评论(0编辑  收藏  举报

导航