I have a WPF form with a couple of buttons, and for each button I have error handling code:
try {bla bla}
catch(Exception e){
more bla
}
If it is a WinForms app, you can encapsulate the Application.Run() call in a try catch statement, although I really wouldn't recommend this, you should only be using try catches where they are absoloutely needed and deal with exceptions whereever possible before just relying on catches.
I know this method works though as I had to use it temporarily once to do some cleaning up on the crashing of an application.
There are multiple possibilities:
The answer depends on your platform. In a web application you can bind the Application_Error
event in Global Asax. In WCF you can inject an error handler of type System.ServiceModel.Dispatcher.IErrorHandler into the WCF stack, in forms applications you can bind the ThreadException event.
Using it may imho be a good idea in some situations since you prevent showing exception details to the user, but also indicates a certain slobbyness regarding exception handling. I have used WCF error handlers to convert domain exceptions to http status code which is simple. Whether it is a good practice or not I do not know. For asp.net applications it is also worth looking at elmah available via NuGet
.
It is also possible to write a simple exception handler that allows you to repeat the try/catch blocks by sending reoutines as Func
or Action
like this
var eh = new ExceptionHandler();
eh.Process ( () => throw new SillyException());
with class ExceptionHandler
class ExceptionHandler
{
public T Process(Func<T> func())
{
try { return func(); }
catch(Exception ex) { // Do stuff }
}
public void Process(Action a)
{
try { action() }
catch(Exception ex) { // Do stuff }
}
}
You can subscribe to AppDomain.UnhandledException
event (see MSDN) to accomplish this. Ideally, this happens when bootstrapping your application. You can find the AppDomain you're executing in via AppDomain.Current
.
Add this to you Global.asax
:
protected void Application_Error(object sender, EventArgs e) {
Exception currentException = Server.GetLastError();
// your handling code goes here ...
Server.ClearError();
}