且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在c#windows窗体中处理未处理的异常

更新时间:2022-12-24 11:37:25

在这个级别上处理它会给你一些帮助。 System.Windows.Forms 有一个特殊的机制来处理主事件循环中的所有异常,你需要在所有情况下使用它。我在过去的答案中对此进行了描述:

错误记录和屏幕截图。 [ ^ ],

捕捉异常 [ ^ ],

处理类库(dll)中的异常 [ ^ ]。



(WPF有非常相似的机制。)



现在,在顶部其中,你可能需要对其他人进行异常处理r,极少数,战略选择的地方,我称之为能力点。有时你需要重新抛出然后在不同级别的后续处理。此外,您需要捕获每个线程的顶部堆栈帧上的所有异常(除非您开发一些类似于我为表单描述的机制)。请参阅我过去的其他答案:

异常详情:系统。 Runtime.InteropServices.COMException:由于以下错误,检索具有CLSID {0006F03A-0000-0000-C000-000000000046}的组件的COM类工厂失败:... [ ^ ],

当我运行一个应用程序时,会捕获一个异常如何处理这个? [ ^ ],

图片取自网络摄像头未保存在服务器上 [ ^ ],

扔。 .then ... rethrowing [ ^ ]。



一般来说,很少会处理异常;在大多数情况下,你应该让它们从当前的堆栈框架中向上传播。这旨在让您很好地隔离常规的异常行为。了解异常如何工作是很好的。它们就像一种时间机器。我试着在这里解释一下:

C#构造函数中的异常会导致来电者分配到失败? [ ^ ] ,

存储位置操作系统中的.net异常 [ ^ ]。



-SA
Handling it on this level will give your little help. System.Windows.Forms has a special mechanism of handling all exceptions in the main event loop, something you really need to use in all cases. I described it in my past answers:
Error Logging and Screen Shot.[^],
Catching an Exception[^],
Handling exceptions in class library (dll)[^].

(WPF has very similar mechanism.)

Now, on top of it, you may need to do exception handling on some other, very few, strategically chosen places, which I call "competency points". Sometime you need to re-throw then to later handling on different level. Besides, you need to catch all exceptions on top stack frame of each thread (unless you develop some mechanism similar to the one I described for forms). Please see my other past answers:
Exception Details: System.Runtime.InteropServices.COMException: Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error:...[^],
When i run an application an exception is caught how to handle this?[^],
Image taken from Webcam not getting saved on the server[^],
throw . .then ... rethrowing[^].

Generally, exceptions should rarely be handled; in most cases, you should just let them propagate up, out of your current stack frame. This is designed to allow you to well isolate exceptional behavior from "regular". It's good to understand how exception works in general. They are like a kind of time machine. I tries to explain it here:
Does Exception in C# Constructor Cause Caller Assignment to Fail?[^],
where was stored .net exceptions in operating system[^].

—SA