1.运行图片
2.源码
using System ;
using System. Collections. Generic ;
using System. Linq ;
using System. Threading. Tasks ;
using System. Windows. Forms ;
namespace 捕捉全局异常
{
internal static class Program
{
[ STAThread]
static void Main ( )
{
Application. SetUnhandledExceptionMode ( UnhandledExceptionMode. CatchException) ;
Application. ThreadException += Application_ThreadException;
AppDomain. CurrentDomain. UnhandledException += CurrentDomain_UnhandledException;
Application. EnableVisualStyles ( ) ;
Application. SetCompatibleTextRenderingDefault ( false ) ;
Application. Run ( new Form1 ( ) ) ;
}
private static void CurrentDomain_UnhandledException ( object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e. ExceptionObject as Exception ;
if ( ex != null )
{
MessageBox. Show ( $"发生了未处理的异常: { ex. Message } " , "错误" , MessageBoxButtons. OK, MessageBoxIcon. Error) ;
}
else
{
MessageBox. Show ( $"发生了未处理的非托管异常" , "错误" , MessageBoxButtons. OK, MessageBoxIcon. Error) ;
}
}
private static void Application_ThreadException ( object sender, System. Threading. ThreadExceptionEventArgs e)
{
MessageBox. Show ( $"发生了未处理的异常: { e. Exception. Message } \r\n" + $"错误的位置: { e. Exception. StackTrace } " , "错误" , MessageBoxButtons. OK, MessageBoxIcon. Error) ;
}
}
}
3,使用方法---->不用弹窗的方式,可以用写Log的方式写出来。