C# 返回自定义异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15993003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:41:42  来源:igfitidea点击:

Returning a custom exception

c#exception

提问by JohnyMotorhead

I am trying to implement my own Exception class in C#. For this purpose I have created a CustomException class derived from 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) { }
}

Then I use it

然后我用它

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

I'm expecting I will get my exception but all I get is a standard DivideByZeroException. How can I catch a divide by zero exception using my CustomException class? Thanks.

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

采纳答案by Alexei Levenkov

You can't magically change type of exception thrown by existing code.

你不能神奇地改变现有代码抛出的异常类型。

You need to throwyour exception to be able to catch it:

您需要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();
}

回答by Dzmitry Martavoi

First of all, if you want to see your own exception, you should throwit somewhere in your code:

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

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

   return x/y; 

}

then:

然后:

int a = 5;
int b = 0;
try
{
      a.DivideBy(b);
}
catch(CustomException)
{
//....
}