I've seen in multiple projects a kind of catch all exception to catch all unexpected exception so the app won't crash, i see this usually with :
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(myUnexpectedExhandler);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(threadExHandler);
Is this a good or bad practice.
The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.
As far as the compiler is concerned, it's enough to just catch an exception. You don't really have to do anything about it. This is valid, the compiler doesn't complain but what this code does is very bad.
Why is catch(Exception) almost always a bad idea ? Because exceptions if they are catched in the code, you need to handle them properly. And we cannot handle all types of exceptions. Some of the exceptions we cannot deal with it and they makes the application unstable like Thread abort exception.
So in general, catching generic exceptions is bad unless you are 100% sure that you know exactly which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead. A similar rule here is never throw exceptions of type System. Exception.
Catching exceptions at the top level of your project is fine and correct. There, you can do things such as log it, report the details back to your team, etc. Exceptions should definitely be published somewhere if at all possible -- that helps a lot in terms of developing a rock-solid product (see Jeff Atwood's blog post "Exception-Driven Development" for a commentary on this).
What is bad practice is catching exceptions inappropriately further down the call stack. The only time you should catch an exception is when you know exactly what to do with it. Certainly, you should never, ever, ever, ever silently swallow exceptions.
Overall, I would say it is entirely up to you, but for me it depends on what phase a given project is currently in. During initial development of any project, I prefer uncaught exceptions to display a nice descriptive error message with what line of code it bombed on so I can fix it.
Once a site matures, however, I use a custom ErrorHandler class I've built and have all errors logged into a database table, and also have an hourly (or daily) error list e-mailed to the developer in charge of the project. Special errors that require delicate handling will usually have a try/catch around the specific lines of code that could break.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With