======如何捕捉意外的异常?======

javaname10 2007-06-29 11:47:35
比如我在我觉得能出差的地方都加上了try catch来捕捉异常。但是有时我的程序还是会出现什么:XXX遇到异常需要关闭........发送 ...不发送。

一点程序就关了。也不知道是那儿的错误。应该怎么捕捉这样不知道异常的错误。
...全文
154 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
javaname10 2007-06-29
  • 打赏
  • 举报
回复
请问谁能提供个例子。
riluo 2007-06-29
  • 打赏
  • 举报
回复
学习
jinta2001 2007-06-29
  • 打赏
  • 举报
回复
使用Application.ThreadException
jinta2001 2007-06-29
  • 打赏
  • 举报
回复
MSDN上面的例子已经是很清楚的了
// Creates a class to throw the error.
public class ErrorHandler : System.Windows.Forms.Form {

// Inserts the code to create a form with a button.

// Programs the button to throw an exception when clicked.
private void button1_Click(object sender, System.EventArgs e) {
throw new ArgumentException("The parameter was invalid");
}

public static void Main(string[] args) {
// Creates an instance of the methods that will handle the exception.
CustomExceptionHandler eh = new CustomExceptionHandler();

// Adds the event handler to to the event.
Application.ThreadException += new ThreadExceptionEventHandler(eh.OnThreadException);

// Runs the application.
Application.Run(new ErrorHandler());
}
}

// Creates a class to handle the exception event.
internal class CustomExceptionHandler {

// Handles the exception event.
public void OnThreadException(object sender, ThreadExceptionEventArgs t)
{
DialogResult result = DialogResult.Cancel;
try
{
result = this.ShowThreadExceptionDialog(t.Exception);
}
catch
{
try
{
MessageBox.Show("Fatal Error", "Fatal Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}

// Exits the program when the user clicks Abort.
if (result == DialogResult.Abort)
Application.Exit();
}

// Creates the error message and displays it.
private DialogResult ShowThreadExceptionDialog(Exception e) {
string errorMsg = "An error occurred please contact the adminstrator with the following information:\n\n";
errorMsg = errorMsg + e.Message + "\n\nStack Trace:\n" + e.StackTrace;
return MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
}
}

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧