I\'ve started using try-catch blocks (a bit late, I know!), but now I\'m not sure what to do with the exception once I\'ve caught it. What should I do?
First, if there is no way for your application to handle the exception then you shouldn't catch it in the first place (logging can be done via exception event handlers without catching).
If there is something you can do then do that. For example, roll back the transaction and report it failed to the user. This is going to depend on your application.
If you don't want to do anything with it, you can always just do try/finally rather then try/catch/finally
Rule of thumb for exception handling--If you don't know what to do with it, don't catch it.
Corollary to the rule of thumb for exception handling--Handle exceptions at the last responsible moment. If you don't know if this is the last responsible moment, it isn't.
Well, That depends primarily if you are making money from your application or not. By my experience, nobody (who paid for an application) likes to see it crashing and closing, instead they prefer a short and explanatory message about the error and a second chance to continue whatever they were doing plus a chance to save/export their modified data. IMO a best practice is to catch everything that can cause something wrong out of your control, like I/O operations, networking related tasks, e.t.c. and display a relevant message to the user. In case that an exception is thrown due to a logic related error is better not to catch it since this will help you to find and correct the actual error.
Hope this helps.
Depending on the type of application, consider either a global logging handler (i.e. 'Application_Error' for ASP.NET applications) or using a pre-built open source or MSFT provided exception handling framework.
The Exception Handling Application Block as part of the Enterprise Library 5.0 is a suggested framework to use.
Aside from logging, I agree that exceptions need not be explicitly caught unless you need to do something meaningful with them. And the worst mistake is just to 'Catch' and then 'Throw' again as this messes the StackTrace up.
FYI, you don't have to use the catch to have a finally statement.
Sometimes people throw a new exception that is more firendly and add the original exception as the inner exception.
Often this is used to log the error to a file or send an email to an operator.
Sometimes, especially with SQL, it may just mean a duplicate key which means, for example, please choose another username, that one is already taken - it's all down to your application.