Osh*_*Nad 24 .net c# exception-handling winforms
反正有没有捕获代码中任何地方引发的探测?我想捕获异常并以类似的方式处理它们,而不是为每个功能编写try catch块.
Cha*_*thJ 37
在Windows窗体应用程序中,当在应用程序中的任何位置(在主线程上或在异步调用期间)抛出异常时,您可以通过在Application上注册ThreadException事件来捕获它.通过这种方式,您可以以相同的方式处理所有异常.
Application.ThreadException += new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod);
private static void MyCommonExceptionHandlingMethod(object sender, ThreadExceptionEventArgs t)
{
//Exception handling...
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*haw 23
我认为这是一个接近,因为你可以在win form应用程序中找到你想要的东西.
http://msdn.microsoft.com/en-us/library/ms157905.aspx
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms errors to go through
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Run Code Online (Sandbox Code Playgroud)
如果不执行所有这些步骤,您将面临无法处理异常的风险.
Jod*_*ell 18
显而易见的答案是将异常处理程序放在执行链的顶部.
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new YourTopLevelForm());
}
catch
{
//Some last resort handler unware of the context of the actual exception
}
}
Run Code Online (Sandbox Code Playgroud)
这将捕获主GUI线程上发生的任何异常.如果您还想全局捕获在所有线程上发生的异常,您可以订阅AppDomain.UnhandledException事件并在那里处理.
Application.ThreadException +=
new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod)
private static void MyCommonExceptionHandlingMethod(
object sender,
ThreadExceptionEventArgs t)
{
//Exception handling...
}
Run Code Online (Sandbox Code Playgroud)
代码复制自Charith J的答案
现在提出建议......
这些选项应该仅作为最后的手段使用,例如,如果您想要禁止从呈现给用户的意外未捕获的异常.当你知道关于异常情况的某些事情时,你应该尽可能早地抓住.更好的是,您可以对此问题采取一些措施.
结构化异常处理可能看起来像是一个不必要的开销,你可以解决所有问题,但它存在,因为情况并非如此.更重要的是,这项工作应该在编写代码时完成,而开发人员的逻辑则是新鲜的.不要懒惰,留下这项工作以供日后使用,或让一些更有经验的开发人员接受.
如果您已经知道并且这样做,请道歉.