是这样的:
我的winform程序有许多模块,很多地方用了
try
{...}
catch
{...}
来保护,因为代码很多,有的地方写了,有的地方没写,而这样写也很麻烦,
有什么办法统一在一个地方写,能捕捉到没有捕获过(因为有些代码已经编写try...catch...保护)的任何异常?
期待高手回答
我的winform程序有许多模块,很多地方用了
try
{...}
catch
{...}
来保护,因为代码很多,有的地方写了,有的地方没写,而这样写也很麻烦,
有什么办法统一在一个地方写,能捕捉到没有捕获过(因为有些代码已经编写try...catch...保护)的任何异常?
期待高手回答
在业务层和UI层捕捉异常就可以了
你的情况只能在每个方法加一个
try
{...}
catch
{...}
方法的所有代码都包括在try里
void A()
{
throw new xxxException();
}
这样是没必要的,因为这样你没办法去关心比较重要的异常
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(AppThreadException);
Application.Run(new Form1());
}private static void AppThreadException(object source, System.Threading.ThreadExceptionEventArgs e)
{
string errorMsg = string.Format("未处理异常: \n{0}\n", e.Exception.Message);
errorMsg += Environment.NewLine;DialogResult result = MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);if (result == DialogResult.Abort)
{
Application.Exit();
}
}
Application.ThreadException += getmessage;
private static void getmessage(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
}