Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching base Exception class in .NET

Tags:

I keep hearing that

catch (Exception ex)

Is bad practise, however, I often use it in event handlers where an operation may for example go to network, allowing the possibility of many different types of failure. In this case, I catch all exceptions and display the error message to the user in a message box.

Is this considered bad practise? There's nothing more I can do with the exception: I don't want it to halt the application, the user needs to know what happened, and I'm at the top level of my code. What else should I be doing?

EDIT:

People are saying that I should look through the stack of calls and handle errors specifically, because for example a StackOverflow exception cannot be handled meaningfully. However, halting the process is the worst outcome, I want to prevent that at all costs. If I can't handle a StackOverflow, so be it - the outcome will be no worse than not catching exceptions at all, and in 99% of cases, informing the user is the least bad option as far as I'm concerned.

Also, despite my best efforts to work out all of the possible exceptions that can be thrown, in a large code-base it's likely that I would miss some. And for most of them the best defense is still to inform the user.

like image 393
Grokys Avatar asked Sep 22 '08 12:09

Grokys


Video Answer


1 Answers

The bad practice is

catch (Exception ex){}

and variants:

catch (Exception ex){ return false; }

etc.

Catching all exceptions on the top-level and passing them on to the user (by either logging them or displaying them in a message-box, depending on whether you are writing a server- or a client-application), is exactly the right thing to do.

like image 182
Rasmus Faber Avatar answered Oct 25 '22 22:10

Rasmus Faber