Search code examples
c#c#-4.0fortify

How to handle all Exception in Custom Exception Class?


I want to handle all exceptions to a Custom Exception Class. I don't want to raise Custom Exception in try block I want to every exception will catch by my custom Exception Class.

I don't want to do this:

private static void Main(string[] args)
{
    try
    {
        Console.WriteLine("Exception");
        throw new CustomException("Hello World");
    }
    catch (CustomException ex)
    {
        Console.WriteLine(ex.Message);
    }
    Console.ReadLine();
}

I want this:

private static void Main(string[] args)
{
    try
    {
        Console.WriteLine("Exception");
        throw new Exception("Hello World");
    }
    catch (CustomException ex)
    {
        Console.WriteLine(ex.Message);
    }
    Console.ReadLine();
}

public class CustomException : Exception
{
    public CustomException()
    {
    }

    public CustomException(string message) : base(message)
    {
    }

    public CustomException(string message, Exception innerException)
        : base(message, innerException)
    {
    }

    protected CustomException(SerializationInfo info, StreamingContext context) 
        : base(info, context)
    {
    }
}

Hope you get my question.


Solution

  • You cannot change the existing Exception classes.

    But you can catch the exception and convert it to a CustomException:

    try
    {
        try
        {
            // Do you thing.
        }
        catch(Exception e)
        {
            throw new CustomException("I catched this: " + e.Message, e);
        }
    }
    catch(CustomException e)
    {
        // Do your exception handling here.
    }
    

    I don't know it this is what you want, but I think this is the closest you can do.