C# catch any exiting exception
Is it possible to catch an exception from anywhere in a console app that would cause the app to terminate? I'm trying to do this without having and try{} catch{} around ever开发者_StackOverflowything.
You can use AppDomain.CurrentDomain.UnhandledException
event which will catch all unhandled exceptions.
Also check this thread for reference: .NET Global exception handler in console application
Try - catch in your main will not be able to catch exceptions from other threads, for example.
Exceptions "bubble up" to the calling method so having a try-catch block in your Main
method is enough to catch everything.
The next important question is what you are going to do with exceptions at top level. Once you are back at that level it is often impossible to make any relevant error recovery except retrying the operation. It is often much better to catch any exceptions that are likely to occur at the site where they are thrown and implement recovery code there.
Go to Debug->Exceptions (Ctrl+D,E) and check appropriate Exception you want to handle. There's an option to break on all 'Thrown' and 'User-unhandled' exception.
You probably want to select 'Common Language Runtime Exception' that are 'Thrown' and 'User-unhandled'. This would break execution any time a CLR exception occurs.
See Most Useful VS Feature No One Knows About
AppDomain.CurrentDomain.UnhandledException += OnCurrentDomain_UnhandledException;
//in windows forms you need also to add these two lines
Application.ThreadException += OnApplication_ThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
In a console app you can simply wrap the Main loop in a Try Catch Block
. You should know that there are a handful of exceptions that will cause the application to terminate without hitting this block.
Also power failure and setting Environment.FailFast
to true will ignore this block.
StackoverflowException msdn docs (You can actually catch it you just shouldn't knowledge here)
Environment.FailFast msdn docs
Check out the AppDomain.CurrentDomain.UnhandledException API for creating an app-global exception handler. And here's a nice blog post about implementing/using it with C# and VB.
Also reconsider your approach to exception handling. Structured exception handling should save you the trouble of needing to deal with 'errors all over the place' because the exceptions percolate up the call stack automatically. This means that if you take advantage of exception handling properly then you will have a small number of points in your code where you handle particular exceptions. You definitely should not try and catch everywhere, all the the time.
A try{} / catch{Exception} in your top-level will catch anything thrown from below before it becomes an "uncaught exception".
精彩评论