Search code examples
c#try-catch

C# Do exceptions IDs exist


My software uses Try Catch to catch errors; recently an error occurred (a timeout connection to the database) and a Messagebox.Show() pops up alerting the user of the issue. The end users of this in house software are not IT literate at all. The lady who received this message asked me with whom she had lost a connection with (I honestly think she thought it was a spiritual 'connection' since she looks like a hippy).

So what I would like to do is simplify the error messages.

Things I've considered:

I could check/compare the ex.Message string to a list of strings I want to cater for and if it matches one I will display the simplified version. IMO, not realistic.

I then thought having multiple catches, and if it's of a certain type, to display the simple message. But how messy is my code going to be! Not only that, it's also probably going to end up with misleading messages as not all (eg) TimeOutExceptions are the same.

Or, I have to try and write my own Exception type to cater for this.

I then though it would be really handy if each .NET exception had an associated ID - that way, I could write a nice case statement with each ID and my own nice and easy to ready/understand message.

Has anyone else considered this before and did they find any suitable arrangements. Or is it better to just put a message on screen saying "Error - an email has been sent to the software vendor...")?


Solution

  • If ever you write code like catch (Exception ex) then you are doing something wrong. You should always catch specific exceptions for coding situations that are exceptional.

    Have a read of Eric Lippert's "Vexing exceptions" blog entry.

    Catching exceptions and just displaying the message is in the "boneheaded" category of exceptions. You should never have them.

    Instead you should only have exceptions of the other three types expounded by Eric. And you should catch the specific exception type involved, not the generic Exception type.

    If you catch specific exceptions then you can present a very reasonable message to the end user - even providing information about how to solve the problem.

    Better still, without all the generic exception catching your code will be easier to debug, cleaner and more terse. The major predictor for bugs in code is the actual lines of code you write. Write less code and have less bugs.

    So my suggestion is change your code design and handle the exceptions appropriately.