如何处理自定义异常类中的所有异常

本文关键字:异常 自定义异常 何处理 处理 | 更新日期: 2023-09-27 18:34:57

我想处理自定义异常类的所有异常。我不想在 try 块中引发自定义异常,我希望我的自定义异常类会捕获每个异常。

我不想这样做:

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

我想要这个:

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)
    {
    }
}

希望你明白我的问题。

如何处理自定义异常类中的所有异常

不能更改现有的异常类。

但是您可以捕获异常并将其转换为自定义异常:

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.
}

我不知道这是你想要的,但我认为这是你能做的最接近的。

我猜你想实现这一点,因为你想把每个异常都当作一个自定义异常来对待。那么,为什么不以这种方式对待每一个异常呢?以处理自定义异常的方式处理每个异常。如果您不想将某些异常作为自定义异常处理,那么您想要实现的不是您问题中的内容。

如果您绝对必须将所有内容视为自定义异常,则可以执行以下操作;

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

但是,我认为这不是一个明智的方法。