Type initializer (static constructor) exception handling

六眼飞鱼酱① 提交于 2019-11-30 12:23:27

So you could wrap the critical parts in try/ catch and at least that means the type won't fail to initialize, but surely if the initialization code is that critical, then this behavior is actually good - the type is not usable in this uninitialized state.

The other option is to do it as a singleton - each time you try and get the Instance you can create the type correctly, until you are successful, even if it fails the first time.

You would still need some error handling on the caller in case Instance returns you null the first (or second etc.) time.

Edit: And if you don't want a singleton, then just have your instance constructor initialize the static parts

e.g.

private object _lock = new object()
private bool _initialized;

public T()
{
   lock(_lock)
   {
      if(!_initialized)
      {
         try
         {
           //Do static stuff here
         }
         catch(Exception ex_)
         {
           //Handle exception
         }
      } 
   }
}

The lesson here is pretty simple: don't do anything in a static constructor that could reasonably fail.

The workaround I used in the past is creating a Singleton. Make a static constructor fail if and only if the failure means the whole application can't run.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!