开发者

Exception handling in class constructor

this case is bothering me since morning. Is it good practice to call garbage collector in class constructor if it throws Exception ? I have something like this:

public MyClass(/* some arguments */)
{
    try 
    {
      //do stuff...
    } catch(Exception e) {
      //do stuff, save logfile
      GC.SuppressFinalize(this);
    }

}

The reason that I did it like this is that if it threw Exception (usualy NullreferenceException) I want to log it in text file and I don't need/want this object anymore. but is it good practice? If 开发者_运维技巧not how to do it properly?


Your code doesn't call the garbage collector - it merely suppresses the finalizer, which is only important if your class has a finalizer, which is pretty unlikely.

It's fair enough to log the exception, but currently you're just catching it, which means the constructor will return with no errors. That's almost certainly not a good idea. I suggest you probably want:

try 
{
  //do stuff...
} catch(Exception e) {
  //do stuff, save logfile
  throw;
}

Having said that, I would normally try to centralize exception handling anyway, putting it a long way up the call stack and putting all logging in there. It would be pretty rare to put the logging within a constructor, IMO.

Unless you've published the this reference from within your constructor, the newly created object will be eligible for garbage collection anyway - you don't need to do anything else. If you implement IDisposable in your class you should be careful to release any resources you've already required within the constructor, but in most cases you can just let the exception bubble up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜