Can following code be considered as a good practice? If not, why?
try
{
// code that can cause various exceptions.
There's an excellent blog post by Eric Lippert, "Vexing exceptions". Eric answers your question with some universal guidelines. Here is a quote from the "sum up" part:
- Don’t catch fatal exceptions; nothing you can do about them anyway, and trying to generally makes it worse.
- Fix your code so that it never triggers a boneheaded exception – an "index out of range" exception should never happen in production code.
- Avoid vexing exceptions whenever possible by calling the “Try” versions of those vexing methods that throw in non-exceptional circumstances. If you cannot avoid calling a vexing method, catch its vexing exceptions.
- Always handle exceptions that indicate unexpected exogenous conditions; generally it is not worthwhile or practical to anticipate every possible failure. Just try the operation and be prepared to handle the exception.