在 C# 中引发异常的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/335933/
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-03 23:42:06  来源:igfitidea点击:

What's the best way to raise an exception in C#?

c#exception

提问by Ben Griswold

I traditionally deploy a set of web pages which allow for manual validation of core application functionality. One example is LoggerTest.aspx which generates and logs a test exception. I've always chosen to raise a DivideByZeroException using an approach similar to the following code snippet:

传统上,我会部署一组允许手动验证核心应用程序功能的网页。一个例子是 LoggerTest.aspx,它生成并记录一个测试异常。我总是选择使用类似于以下代码片段的方法来引发 DivideByZeroException:

try
{
   int zero = 0;
   int result = 100 / zero;
}
catch (DivideByZeroException ex)
{
   LogHelper.Error("TEST EXCEPTION", ex);
}

The code works just fine but I feel like there must be a more elegant solution. Is there a best way to raise an exception in C#?

代码工作得很好,但我觉得必须有一个更优雅的解决方案。是否有在 C# 中引发异常的最佳方法?

采纳答案by GalacticCowboy

try
{
  throw new DivideByZeroException();
}
catch (DivideByZeroException ex)
{
  LogHelper.Error("TEST EXCEPTION", ex);
}

回答by Jesse Millikan

Short answer:

简短的回答:

throw new Exception("Test Exception");

You will need

你会需要

using System;

回答by Tablet

throw exceptionhere;

在这里抛出异常;

Isn't it?

不是吗?

Example I found was

我发现的例子是

        if (args.Length == 0)
        {
            throw new ArgumentException("A start-up parameter is required.");
        }

回答by Greg Beech

throw new DivideByZeroException("some message");?

throw new DivideByZeroException("some message");?

Or am I missing something?

或者我错过了什么?

回答by yuriks

For testing purposes you probably want to create a specific class (maybe TestFailedException?) and throw it rather than hiHymaning another exception type.

出于测试目的,您可能想要创建一个特定的类(也许是 TestFailedException?)并抛出它而不是劫持另一个异常类型。

回答by Collin K

If you're just testing LogHelper's Error method, why even throw the exception? You just need a one-liner:

如果您只是测试 LogHelper 的 Error 方法,为什么还要抛出异常?你只需要一个单线:

LogHelper.Error("TEST EXCEPTION", new Exception("This is a test exception"));

回答by James Curran

So, let me put in a pitch for continuing to do it the way you were. You don't want to test what happens when a DivideByZeroExceptionis thrown; you want to test what happens when a divide by zero actually occurs.

所以,让我提出一个继续像你一样做的事情。您不想测试DivideByZeroException抛出a 时会发生什么;您想测试实际发生除以零时会发生什么。

If you don't see the difference, consider: Are you really sure when you want to check for NullRefernceExceptionand when for ArgumentNullException?

如果您没有看到差异,请考虑:您真的确定什么时候要检查NullRefernceExceptionArgumentNullException什么时候要检查吗?

回答by Ben Griswold

Thanks for the feedback. I've marked GalacticCowboy's answer as correct as it is obviously the correct answer based on the way the question is phrased.

感谢您的反馈。我已将 GalacticCowboy 的答案标记为正确,因为根据问题的措辞方式,这显然是正确的答案。

For those thinking "there's got to be more to this question", you're right. In essence I was looking for a best way to raise/cause/simulate an exception. As James Curran stated, it's the occurrence of the exception rather than the throwing of an exception which I'm after. Forcing a DivideByZeroException is my default strategy though I thought there might be another way or maybe even a better exception to force.

对于那些认为“这个问题必须有更多内容”的人来说,你是对的。从本质上讲,我正在寻找一种引发/导致/模拟异常的最佳方法。正如 James Curran 所说,这是异常的发生,而不是我所追求的异常的抛出。强制 DivideByZeroException 是我的默认策略,尽管我认为可能有另一种方式,甚至可能是更好的强制例外。

More than likely there's no difference between throwing and "raising" an exception. The majority of answers seem to be of this opinion at least.

抛出和“引发”异常很可能没有区别。大多数答案似乎至少是这种观点。

Thanks again for the feedback and sorry if the question was vague.

再次感谢您的反馈,如果问题含糊,我们深表歉意。

回答by Charles Bretana

Build a custom exception for testing purposes ? Then you could add whatever custom properties you want the exception to carry with it on it's way through the exception handling / logging process...

为测试目的构建自定义异常?然后,您可以添加任何您希望异常在异常处理/记录过程中携带的自定义属性......

 [Serializable]
 public class TestException: ApplicationException
 {
     public TestException(string Message, 
                  Exception innerException): base(Message,innerException) {}
     public TestException(string Message) : base(Message) {}
     public TestException() {}

     #region Serializeable Code
     public TestException(SerializationInfo info, 
           StreamingContext context): base(info, context) { }
     #endregion Serializeable Code
 }

in your class

在你的班级

 try
 {  
      throw new TestException();
 }
 catch( TestException eX)
 {  
    LogHelper.Error("TEST EXCEPTION", eX);
 }

回答by Steve Pitchers

Does

System.Diagnostics.Debug.Assert(condition);

give you an alternative?

给你一个选择?

Perhaps then use

也许然后使用

catch (AssertionException) { }

to log a test failure.

记录测试失败。

See also C# - What does the Assert() method do? Is it still useful?and http://en.csharp-online.net/Assert.

另请参阅C# - Assert() 方法的作用是什么?它还有用吗?http://en.csharp-online.net/Assert