11

I need to change specific system exception message with my custom one.

Is it bad practice to catch an exception and inside the catch block check if the system exception message matches a specific string and if so, throw my custom exception?

try
{
    ...
}
catch (System.Security.Cryptography.CryptographicException ex)
{
    if (ex.Message.Equals("The specified network password is not correct.\r\n", StringComparison.InvariantCultureIgnoreCase))
        throw new Exception("Wrong Password");
    else
        throw ex;
}

Or is there a better way to achieve this.

3
  • The if(ex.Message == "...") will only work for English locales. Commented Jul 12, 2015 at 12:13
  • By that do you mean that if the user is from Spain, for example, the C# exception will be different? I thought it depends on the server's locale. Commented Jul 13, 2015 at 6:05
  • The Message is set wherever the exception is thrown... And there the locale has to be en. Commented Jul 13, 2015 at 8:00

2 Answers 2

12

To save unwinding the stack when checking the message you could use user-filtered exception handlers - https://learn.microsoft.com/en-us/dotnet/standard/exceptions/using-user-filtered-exception-handlers. This will maintain the stack trace for the unfiltered exceptions.

try
{
    // ...
}
catch (System.Security.Cryptography.CryptographicException ex) when (ex.Message.Equals("The specified network password is not correct.\r\n", 
StringComparison.InvariantCultureIgnoreCase))
{
    throw new InvalidPasswordException("Wrong Password", ex);
}
Sign up to request clarification or add additional context in comments.

Comments

9

There's nothing inherently wrong with throwing an exception within a catch statement. However there are a couple of things to bear in mind:

Rethrow the exception using "throw" not "throw ex", otherwise you will loose the stack trace.

From [Creating and Throwing Exceptions] 1.

Do not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.

If the CrytographicException is really not suitable for you, you could create a specific exception class to represent an invalid password:

try
{
    ...
}
catch (System.Security.Cryptography.CryptographicException ex)
{
    if (ex.Message.Equals("The specified network password is not correct.\r\n",
            StringComparison.InvariantCultureIgnoreCase))
        throw new InvalidPasswordException("Wrong Password", ex);
    else
        throw;
}

Note how the original exception is preserved in the new InvalidPasswordException.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.