Michael Kniskern
Michael Kniskern

Reputation: 25280

Programmatically suppressing exceptions in C#

I have the following try-catch statement and I do not want to not throw the exception if the message property contains 'My error' in the text.

How can I programmatcially accomplish this? Also, would this be considered code-smell?

try
{
}
catch(Exception e)
{
    if(e.Messages.Contains("My error"))
    {
       //want to display a friendly message and suppress the exception
    }
    else
    {
        throw e;
    }
}

Upvotes: 1

Views: 5562

Answers (4)

Joshua
Joshua

Reputation: 43317

When I throw Exception rather than a derived class I always mean a failed assertion. I don't like failing out the backend because we are still able to receive a request (just not that one again). If we're really toast it will just error out on the next request anyway.

When the back end needs to generate an error message I have a ErrorMessage class that inherits from Exception and takes ErrorMessage and ErrorMessageTitle as constructor arguments.

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68717

Your code creates maintainability issues because a simple text change can have strange side effects. You can have your own exception class which inherits from System.Exception. Then instead of having an if you could do the following:

try
{

}
catch(MyException myException) //or just catch(MyException)
{
    //display a friendly message
}

also you don't want to do throw e because it doesn't preserver the Stack, just throw; will do.

Upvotes: 7

Jim Mitchener
Jim Mitchener

Reputation: 9003

You should be catching the specific exception you're looking for. Quite frankly, that code is shocking. You should have something like ...

public class MyCoolException : Exception {
    public MyCoolException(string msg) : base(msg) {}
}

public void MyCoolMethod() {
    // if bad things happen
    throw new MyCoolException("You did something wrong!");
}

Then later in your code you can use it like ...

try {
    MyCoolMethod();
} catch (MyCoolException e) {
    // do some stuff
}

Upvotes: 11

Claudiu
Claudiu

Reputation: 229491

You shouldn't catch errors based on the error test. You should make your own exception class that extends exception:

class MyErrorException : Exception { }

and throw and catch those. (Excuse my syntax if it's wrong, I haven't done C# in a while).

That being said, throwing and catching your own Exceptions instead of propagating them is perfectly normal, and it is how you actually should do exception handling.

Upvotes: 14

Related Questions