Throwing exceptions from a constructor in .NET

2019-04-05 03:54发布

Are there any memory leaks when I throw an exception from a constructor like the following?

class Victim
{
    public string var1 = "asldslkjdlsakjdlksajdlksadlksajdlj";

    public Victim()
    {
        //throw new Exception("oops!");
    }
}

Will the failing objects be collected by the garbage collector?

5条回答
闹够了就滚
2楼-- · 2019-04-05 04:10

It depends on what other resources you've aquired before the exception is thorwn. I don't think throwing exceptions in a constructor is great, but throwing them in finalizers or dispose() is much much worse.

查看更多
Summer. ? 凉城
3楼-- · 2019-04-05 04:12

Throwing exceptions from a constructor should be fine if you have created no unmanaged resources. However, if you do create unmanaged resources in the constructor, the whole body of that constructor, including throws, should be wrapped in a try/catch. To steal JaredPar's great example:

public class Foo : IDisposable { 
  private IntPtr m_ptr;
  public Foo() {
    try
    {
        m_ptr = Marshal.AllocHGlobal(42);
        throw new Exception();
    }
    catch
    {
        Dispose();
        throw;
    }
  }
  // Most of Idisposable implementation ommitted for brevity
  public void Dispose() {
    Marshal.FreeHGlobal(m_ptr);
  }
}

The following would now work:

using ( var f = new Foo() ) {
  // Won't execute, but Foo still cleans itself up
}
查看更多
Evening l夕情丶
4楼-- · 2019-04-05 04:18

Funny, because I helped with a similar question just yesterday.

It's a bigger issue if you have a derived type, because some parts of the derived type will initialize but not others. From a memory perspective it doesn't really matter, because the garbage collector knows what's where. But if you have any unmanaged resources (implement IDisposable) things can get murky.

查看更多
萌系小妹纸
5楼-- · 2019-04-05 04:25

Yes, the garbage collector will reclaim the managed resources already allocated in the object. If you've initialised any unmanaged resources, you will need to clean those up yourself in the normal way.

查看更多
beautiful°
6楼-- · 2019-04-05 04:31

In general this is safe from the perspective of not leaking memory. But throwing exceptions from a constructor is dangerous if you allocate unmanaged resources in the type. Take the following example

public class Foo : IDisposable { 
  private IntPtr m_ptr;
  public Foo() {
    m_ptr = Marshal.AllocHGlobal(42);
    throw new Exception();
  }
  // Most of Idisposable implementation ommitted for brevity
  public void Dispose() {
    Marshal.FreeHGlobal(m_ptr);
  }
}

This class will leak memory every time you try to create even if you use a using block. For instance, this leaks memory.

using ( var f = new Foo() ) {
  // Won't execute and Foo.Dispose is not called
} 
查看更多
登录 后发表回答