Find out where in user code an internal .Net exception originated
I am currently working on an existing Windows Forms application (VB.net), and am busy reworking the exception handling mechanism.
Currently, a lot of methods in the code are just surrounded with try/catch block that catches a generic exception and then calls a utility method that just shows the user a messagebox informing him of the error, and then logging it.
So in a lot of cases no corrective action is taken and the exception is just logged. I k开发者_如何学Pythonnow this probably isn't the best way but that's they way we're gonna have to do it for the near future.
Anyway, I wanted to do this in a more generic way, so I hooked up Application.ThreadException and AppDomain.UnhandledException.
This seems to work well, except for one inconvenience. Whenever an error gets thrown from the .net runtime itself, or a 3rd party control, the stacktrace begins there where the exception is thrown in the framework-methods or 3rd party methods (obviously!).
But it would be handier if I had an easy way of finding out exactly where these exceptions cross the boundary into my code. I would like an easy way of determining (in Application.ThreadException) where in my own code an exception originated.
I am aware this information is contained in the Exception.StackTrace property, but I would like an easy way to get to this specific information seeing as the stacktrace property is one huge string.
Basically I would like the class, method and line number where the exception first bubbled up into my code.
You should try to use this kind of code:
[STAThread] static void Main() {
try {
Application.Run(new Form1());
}
catch (Exception e) {
//do smth with exception
}
}
It will catch exceptions raised only by your code, when in the same time AppDomain.UnhandledException
can be more verbose. This, certainly, will work only for main thread.
精彩评论