23

我正在尝试在 C# 中实现我自己的异常类。为此,我创建了一个从 Exception 派生的 CustomException 类。

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

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

    public CustomException(string format, params object[] args)
        : base(string.Format(format, args)) { }

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

    public CustomException(string format, Exception innerException, params object[] args)
        : base(string.Format(format, args), innerException) { }
}

然后我用它

static void Main(string[] args)
{
    try
    {
        var zero = 0;
        var s = 2 / zero;
    }
    catch (CustomException ex)
    {
        Console.Write("Exception");
        Console.ReadKey();
    }
}

我期待我会得到我的例外,但我得到的只是一个标准的 DivideByZeroException。如何使用我的 CustomException 类捕获除以零异常?谢谢。

4

2 回答 2

29

您不能神奇地更改现有代码引发的异常类型。

您需要throw您的异常才能捕获它:

try 
{
   try
    {
        var zero = 0;
        var s = 2 / zero;
    }
    catch (DivideByZeroException ex)
    { 
        // catch and convert exception
        throw new CustomException("Divide by Zero!!!!");
    }
}
catch (CustomException ex)
{
    Console.Write("Exception");
    Console.ReadKey();
}
于 2013-04-13T21:14:44.423 回答
17

首先,如果您想查看自己的异常,您应该throw在代码中的某处查看:

public static int DivideBy(this int x, int y)
{
    if (y == 0)
    {
        throw new CustomException("divide by zero");
    }

   return x/y; 

}

然后:

int a = 5;
int b = 0;
try
{
      a.DivideBy(b);
}
catch(CustomException)
{
//....
}
于 2013-04-13T21:16:49.067 回答