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.

有帮助吗?

解决方案

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.

其他提示

I am guessing you want to achieve this, beacause you want to treat every exception as if it was a CustomException. Well, why not just treat every exception in that way? Handle every exception the way you would handle your CustomException. If there are some Exceptions that you don't want to handle as a CustomException, then what you want to achieve is not what is in you question.

If you absolutely must treat everything as a CustomException, you could do something like this;

try
{
   //Something that causes any form of exception
}
catch (Exception ex)
{
   throw new CustomException(ex.Message); //Caught and handled in another place.
}

However, I don't think that's a sensible approach.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top