Ahmed El Batrawy Ahmed El Batrawy - 6 days ago 4
C# Question

Custom Exception Handler C#

I have Made custom Exception Handler in C# I want to show a readable message for the user if any Exception occurred.

I have tried to specify the Exception pending on it's Hresult Value but I have a problem that I haven't seen, which is showing Hresult value and the specified exception

class UiException : Exception
{
public string Errormessage { get; set; }
public UiException(Exception e)
: base()
{
string exName = e.Source;
int errorNumber = e.HResult;
if (e.HResult == -2146233080)
Errormessage = "Index was outside the bounds of the array.";

}
}

Answer

You do not want to use HRESULT for exception identification. HRESULT is mainly there for COM interop and is of little use in .NET. I would recommend the following:

  1. Use the type of the base exception to figure out your custom error message. You stay in .NET and it is more flexible. The main advantage in terms of flexibility is that you can easily cover exceptions derived from other exceptions without having to define a fallback. Also, with an ascast you can easily extract further information from the exception (such as the ParameterName of an ArgumentException).
  2. Make your base exception an inner exception. Inner exceptions are there since the dawn of time .NET and therefore are widely supported, e.g. for logging or debugging. Keeping the source of the error is also good for error analysis and general best practice.
  3. There is absolutely no need for your Errormessage property. There is a Message property, which suits your purpose and (like the inner exception) is widely supported.

So your custom exception should look more like this:

class UIException : Exception
{
    public UIException(Exception baseException) :
        base(GetErrorMessage(baseException), baseException)
    {
    }

    private static GetErrorMessage(Exception baseException)
    {
        if (baseException is IndexOutOfRangeException)
        {
            return "Index was outside the bounds of the array.";
        }
        else if (exception is InvalidOperationException)
        {
            //Return exception message
        }
        //... more else if in the chain
        else
        {
            return baseException.Message;
        }
    }
}