Try in the end or try to catch at last

If I have a method like the one below, can I omit the catch block here to achieve the same results ?:

private ClassInstance GetMeANumber()
{
     Resource a = null;

      try
      {
          Resource a = new Resource();
          return a.GetClassInstance();
      }
      catch
      {
          throw;
      }
      finally
      {
          if(a != null)
              a.Dispose();
      }
}
+5
source share
3 answers

Yes, that would be exactly the same.

However, a more common example is IDisposable on Resource. Then you can use with to more accurately understand the same thing.

using (Resource a = new Resource()) {
    return a.GetClassInstance();
}
+18
source

The catch block “just retro” will have several effects that you may or may not like:

  • , , , , , , . .
  • "" , , :
    1. ,
    2. , "" .
, , , .

, , , "" , .

+2

, , , , , . , :

private ClassInstance GetMeANumber()
{
    using (var a = new Resource())
    {
        return a.GetClassInstance();
    }
}
0

All Articles