How do I continue running after an unhandled exception?

拟墨画扇 提交于 2019-11-27 15:53:06

You don't. When you get an AppDomain unhandled exception, your app is no longer in a stable state. Where exactly would you resume to? When you've gotten to that point, your only option, with good reason, is to exit. You could reasonably schedule yourself to run again to make sure the app comes back, but a far better idea is to actually handle the exception at its source and prevent it from being an UnhandledException.

In your app.config add the following element

<runtime>
  <!-- the following setting prevents the host from closing when an unhandled exception is thrown -->
  <legacyUnhandledExceptionPolicy enabled="1" />
</runtime>

You can, and you should use try...catch and handle the exceptions in every situation where an exception might occur. (In languages like Java you can't even compile your code until you catch every exception that the called function might throw or declare explicitly that this particular function won't catch it, so the one that calls it should do it.)

If you want to minimize the cases where you use try...catch some bad situations can be prevented with testing if the necessary conditions are met so you won't even call a function that is known for throwing a particular exception. Like calling

if (myByteArray != null)
{
    myIPAddress = new IPAddress(myByteArray);
}

because this way the IPAddress constructor won't throw an ArgumentNullException.

However in most of the cases this can't be done, especially with networking, because you can't predict if the cable will be cut, the signal will be lost, the database server will crush, etc. in the middle of the transaction. So you should try...catch every time you connect to the network or send data to or receive data from a connection.

AppDomain.CurrentDomain.UnhandledException fires on any unhandled exception on any thread, but since CLR 2.0, the CLR forces application shutdown after your event handler completes. However, you can prevent shutdown by adding the following to your application configuration file:

<configuration>
  <runtime>
    <legacyUnhandledExceptionPolicy enabled="1" />
  </runtime>
</configuration>

I think you need to use Application.ThreadException When you subscribe to Application.ThreadException, unhandled exceptions wont hit the UnhandledException and the app will keep running.

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