I believe I'm following the correct process to implement a custom exception, but the exception arrives in the catch block wrapped in a System.Exception, so the handling for my custom exception doesn't execute.
I create the custom exception class (following examples found online):
using System;
using System.Runtime.Serialization;
namespace La.Di.Da
{
[Serializable]
public class MyCustomException : Exception
{
public MyCustomException()
: base()
{
}
public MyCustomException(string message)
: base(message)
{
}
...
}
I throw the exception, from a lower point in the stack:
...
if (up == down)
{
throw new MyCustomException("Things are topsy-turvy.");
}
...
The exception is caught at an intermediate try-catch. I know such catching-logging-throwing is wrong practice but this code is in an existing method that's called a lot in this application, and regression testing the entire application for my small change isn't an option. Anyway, this catch-throw isn't causing the problem: The exception arrives in this catch already as a System.Exception wrapping my custom exception.
try
{
DoSomeStuff(();
}
catch (Exception ex)
{
LogManager.Instance.LogException(ex);
throw;
}
finally
{
DoSomeCleanup();
}
I have code to catch the custom exception at the next catch up the stack. But the exception arrives as a System.Exception wrapping the custom exception, so my custom exception handling doesn't get executed.
...
try
{
CallAMethod();
}
catch MyCustomException(ex)
{
LogManager.Instance.LogException(ex);
ShowErrorMessage(ex.Message);
}
catch Exception(ex)
{
throw ex;
}
I believe the exception I'm throwing shouldn't be wrapped, so I must be doing something wrong. Any suggestions?