未处理异常的处理
在启动项目的Main函数的开头加上(注意,一定要加在Main函数的最前面):
//捕获GUI异常,无GUI则不需要加
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);//
//捕获线程异常,捕获不了GUI异常
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;//msheng,处理线程异常
译文:
AppDomain.UnhandledException Event
译者:我们知道,对于一些可预见性的错误常常需要在代码外围添加try/cahch块进行错误的捕捉与恢复处理。但是当某个异常我们未添加try/catch进行捕捉时,它便会造成程序出错,此即为未处理异常,未处理异常一般会造成程序终止。
Occurs when an exception is not caught.
当某个异常未被捕捉时此事件将被触发
Remarks
This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. If sufficient information about the state of the application is available, other actions may be undertaken — such as saving program data for later recovery. Caution is advised, because program data can become corrupted when exceptions are not handled.
注意:
此事件提供未捕捉异常的通知。此通知发生在系统报告异常并终止程序之前,因此可以在此通知发生时记录异常日志以供后期调试。另外,如果程序数据未被严重破坏,可采取一些措施保存数据以供程序重启后恢复到异常出现之前的状态。此操作需谨慎。因为一般来讲,程序数据都是被破坏的。
Note
In the .NET Framework versions 1.0 and 1.1, application termination and debugging options are reported to the user before this event is raised, rather than after.
备注:
在.NET Framework 1.0 and 1.1中,系统会先报告异常并终止应用程序,然后才会触发未捕捉异常的通知。
This event can be handled in any application domain. However, the event is not necessarily raised in the application domain where the exception occurred. An exception is unhandled only if the entire stack for the thread has been unwound without finding an applicable exception handler, so the first place the event can be raised is in the application domain where the thread originated.
此事件能在任何App Domain中被处理。但是,我们不必在每个App Domain中都添加该事件的处理器。一个异常仅当整个线程栈都未找到可应用的异常处理器时才被定义为未处理异常,所以此事件最可能被触发的地方是App Domain中线程栈的起点。也就是说,只要在最可能触发该事件的地方添加事件处理器即可。
Note
In the .NET Framework versions 1.0 and 1.1, this event occurs only for the default application domain that is created by the system when an application is started. If an application creates additional application domains, specifying a delegate for this event in those applications domains has no effect.
备注:
在.NET Framework 1.0 and 1.1中,此事件仅适用于默认的App Domain(即应用程序启动时,系统创建的App Domain,即启动项)。如果应用程序创建了额外的App Domain,在该app domian中为此事件指定委托并不会生效。
If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.
如果默认App Domain中添加了UnhandledException处理器,那么任何线程中抛出的未处理异常都会执行该处理器,不论该线程起始于哪个App Domain。如果非默认App Domain中也添加了未处理异常的处理器,那么默认App Domain和非默认App Domain中的未处理异常处理器均会被触发。
(字面翻译:如果UnhandledException事件在默认的App Domain中被处理了,那么在任何线程中的任何未处理异常都会触发该UnhandledException,不管这个线程是起始于哪个App Domain的。如果这个线程起始于一个拥有UnhandledException的App Domain,这个事件会在该App Domain中触发。如果该App Domain不是默认的App Domain,并且默认的App Domain中有UnhandledException的处理器,该事件会在两个App Domain中均被触发。)
For example, suppose a thread starts in application domain “AD1”, calls a method in application domain “AD2”, and from there calls a method in application domain “AD3”, where it throws an exception. The first application domain in which the UnhandledException event can be raised is “AD1”. If that application domain is not the default application domain, the event can also be raised in the default application domain.
例如,假设一个线程起始于AD1 App Domain,并且调用了AD2 App Domain中的一个方法,且该方法又调用了AD3 App Domain中的一个方法,刚好在AD3 App Domain的方法中抛出了一个异常。这个最有可能触发UnhandledException事件的App Domain是AD1。如果AD1不是默认的App Domain,该事件也能触发于默认的App Domain。
Note
The common language runtime suspends thread aborts while event handlers for the UnhandledException event are executing.
备注:
当UnhandledException事件处理器执行的时候公共语言运行时(CLR)会暂停线程终止操作。
If the event handler has a ReliabilityContractAttribute attribute with the appropriate flags, the event handler is treated as a constrained execution region.
如果事件处理器应用了ReliabilityContrac特性,这个事件处理器被当做约束执行区域对待(具体请了解CER,约束执行区域)。
Starting with the .NET Framework 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.
从.NET Framework 4(包括.NET Framework 4)开始,当损坏进程状态的异常如栈溢出,访问无效等发生时,该事件不会被触发,除非此事件处理器应用了security-critical和HandleProcessCorruptedStateExceptionsAttribute特性
In the .NET Framework versions 1.0 and 1.1, an unhandled exception that occurs in a thread other than the main application thread is caught by the runtime and therefore does not cause the application to terminate. Thus, it is possible for the UnhandledException event to be raised without the application terminating. Starting with the .NET Framework version 2.0, this backstop for unhandled exceptions in child threads was removed, because the cumulative effect of such silent failures included performance degradation, corrupted data, and lockups, all of which were difficult to debug. For more information, including a list of cases in which the runtime does not terminate, see Exceptions in Managed Threads.
在 .NET Framework 1.0 and 1.1中,当未处理异常发生于子线程(非主线程)并被运行时捕捉(添加了未处理程序处理器)时,不会造成应用程序终止。但从.NET Framework2.0开始(包括.NET Framework2.0),这种不终止程序的操作被移除了,因为会造成很多负面影响,如性能下降,数据损坏,死锁,而所有这一切都是难以调试的。要想获取更多这方面的信息,包括运行时不会被终止的案例列表,请参阅Exceptions in Managed Threads.
To register an event handler for this event, you must have the required permissions, or a SecurityException is thrown.
要想为此事件注册一个事件处理器,我们必须获得必须的权限,否则会抛出SecurityException异常
For more information about handling events, see Handling and Raising Events.
想要获取更多关于事件处理的信息,请参阅Handling and Raising Events.
Other Events for Unhandled Exceptions
未处理异常的其它事件
For certain application models, the UnhandledException event can be preempted by other events if the unhandled exception occurs in the main application thread.
对于不同的应用程序模型,未处理异常所触发的事件可能不一样
In applications that use Windows Forms, unhandled exceptions in the main application thread cause the Application.ThreadException event to be raised. If this event is handled, the default behavior is that the unhandled exception does not terminate the application, although the application is left in an unknown state. In that case, the UnhandledException event is not raised. This behavior can be changed by using the application configuration file, or by using the Application.SetUnhandledExceptionMode method to change the mode to UnhandledExceptionMode.ThrowException before the ThreadException event handler is hooked up. This applies only to the main application thread. The UnhandledException event is raised for unhandled exceptions thrown in other threads.
在WinForm中,主线程(UI线程)中的未处理异常将触发Application.ThreadException事件。如果此事件被处理,默认的操作下进程不会被终止,而这会使程序处于不确定的状态(数据可能损坏,持续运行下去的逻辑不一定正确等)。主线程不会触发UnhandledException事件,但是此默认行为能够通过修改应用程序的配置文件或者使用Application.SetUnhandledExceptionMode方法进行修改。
Application.SetUnhandledExceptionMode使得UnhandledExceptionMode.ThrowException触发于ThreadException处理器被调用前。注意:在子线程中UnhandledException事件仍会被触发。
Starting with Microsoft Visual Studio 2005, the Visual Basic application framework provides another event for unhandled exceptions in the main application thread. See the WindowsFormsApplicationBase.UnhandledException event. This event has an event arguments object with the same name as the event arguments object used by AppDomain.UnhandledException, but with different properties. In particular, this event arguments object has an ExitApplication property that allows the application to continue running, ignoring the unhandled exception (and leaving the application in an unknown state). In that case, the AppDomain.UnhandledException event is not raised.
从VS2005开始,VB应用程序框架为主线程提供了另外的未处理异常事件。请参阅WindowsFormsApplicationBase.UnhandledException事件。此事件有一个事件参数对象,名字和AppDomain.UnhandledException中的一样,但属性不同。特别地,这个事件参数对象有一个ExitApplication属性,它允许应用程序继续运行,忽略未处理异常(这会使程序处于未知状态)。在主线程中,AppDomain.UnhandledException不会被触发。
Examples
示例
The following example demonstrates the UnhandledException event. It defines an event handler, MyHandler, that is invoked whenever an unhandled exception is thrown in the default application domain. It then throws two exceptions. The first is handled by a try/catch block. The second is unhandled and invokes the MyHandle routine before the application terminates.
以下示例演示了UnhandledException事件。它定义了一个事件处理器MyHandler,只要默认App Domain中有未处理异常抛出它就会被触发。然后,它会抛出两个异常。第一个会被try/catch处理,第二个是未处理的,它会在程序终止之前触发MyHandle路由调用MyHandler处理器
using System;
using System.Security.Permissions;
public class Example
{
[SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
public static void Main()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
try {
throw new Exception("1");
} catch (Exception e) {
Console.WriteLine("Catch clause caught : {0} \n", e.Message);
}
throw new Exception("2");
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
}
}
// The example displays the following output:
// Catch clause caught : 1
//
// MyHandler caught : 2
// Runtime terminating: True
//
// Unhandled Exception: System.Exception: 2
// at Example.Main()
Security
安全
SecurityCriticalAttribute
SecurityCriticalAttribute特性
requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.
需要获得对即时调用者的完全信任。此成员不能被使用partially trusted或者transparent code.
总结:
1. 未处理异常的作用是用于日志记录与数据恢复。
2. 非UI线程中的未处理异常会触发AppDomain.UnhandledException事件。
3. 在默认App Domain中添加的未处理异常处理器肯定会被触发。
如果在其他App Domain中也添加了未处理异常处理器,则两个处理器都会被触发。
4. 不同程序模型未处理异常发生时触发的事件不同。
5. .NET Framework2.0以后(包括.NET Framework2.0)的程序中的未处理异常触发于进程终止之前。而.NET Framework 1.0 and 1.1中的未处理异常触发于程序终止之后。
6. 在添加了未处理异常处理器的前提下,.NET Framework 1.0 and 1.1中,子线程触发未处理异常时程序不会被终止,自.NET Framework2.0后修复了这个问题