返回自定义异常

Joh*_*ead 23 c# exception

我试图在C#中实现我自己的Exception类.为此,我创建了一个派生自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) { }
}
Run Code Online (Sandbox Code Playgroud)

然后我用它

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

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

Ale*_*kov 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();
}
Run Code Online (Sandbox Code Playgroud)

  • 你可能想提一下这样做是个糟糕的主意. (18认同)
  • @Wilbert哪一部分?`2/zero`可能是获取非常特殊异常的最简单方法(`((string)(null)).长度`看起来可能更明显"示例代码 - 不要复制"); 由于许多不同的异常之一(`IOException`,`KeyNotFoundException`等类似可以重新抛出为'CustomerNotFoundException`,可能将InnerException设置为该异常,或者重新抛出异常是非常标准的做法可能不是出于安全要求); 希望很明显嵌套的`try` /`catch`只是一个样本. (2认同)

Dzm*_*voi 17

首先,如果你想看到自己的异常,你应该throw在代码中的某个地方:

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

   return x/y; 

}
Run Code Online (Sandbox Code Playgroud)

然后:

int a = 5;
int b = 0;
try
{
      a.DivideBy(b);
}
catch(CustomException)
{
//....
}
Run Code Online (Sandbox Code Playgroud)