Catch exceptions within a using block vs outside the using block - which is better?

后端 未结 6 1744
甜味超标
甜味超标 2020-12-25 12:29

Is there any difference between these tow pieces of code & which approach is better.

try
{
    using()
    { 
      //Do stuff
    }
}
catch
{
    //Hand         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-25 13:04

    I presume you mean:

    using (var x = new Y(params))
    {
    }
    

    In both cases? Then the obvious difference is the scope of x. In the second case, you could access x in the catch clause. In the first case, you could not.

    I'll also take the opportunity to remind you not to "handle" an exception unless you can really do something about it. That includes logging the exception, which would be ok, unless the environment you're operating in does the logging for you (as ASP.NET 2.0 does by default).

提交回复
热议问题