简体   繁体   English

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

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

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. 一个例子是LoggerTest.aspx,它生成并记录测试异常。 I've always chosen to raise a DivideByZeroException using an approach similar to the following code snippet: 我总是选择使用类似于以下代码段的方法来引发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#中引发异常的最佳方法?

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

Short answer: 简短回答:

throw new Exception("Test Exception");

You will need 你会需要

using System;

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

throw exceptionhere; 抛出异常;

Isn't it? 不是吗?

Example I found was 我发现的例子是

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

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 DivideByZeroException is thrown; 您不想测试抛出DivideByZeroException时会发生什么; you want to test what happens when a divide by zero actually occurs. 你想测试实际发生除以零时会发生什么。

If you don't see the difference, consider: Are you really sure when you want to check for NullRefernceException and when for ArgumentNullException ? 如果您没有看到差异,请考虑:您是否确定何时要检查NullRefernceException以及何时进行ArgumentNullException

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. 正如James Curran所说,这是异常的发生,而不是我所追求的抛出异常。 Forcing a DivideByZeroException is my default strategy though I thought there might be another way or maybe even a better exception to force. 强制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. 再次感谢您的反馈,如果问题含糊不清,请对不起。

        try
        {
            string a="asd";
            int s = Convert.ToInt32(a);
        }
        catch (Exception ex)
        {

            Response.Write(ex.Message);
        }

It will return exception "Input string was not in a correct format. " 它将返回异常“输入字符串格式不正确”。

throw new DivideByZeroException("some message"); ?

Or am I missing something? 或者我错过了什么?

If you're just testing LogHelper's Error method, why even throw the exception? 如果您只是测试LogHelper的Error方法,为什么甚至抛出异常? You just need a one-liner: 你只需要一个单行:

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

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

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

}

// if(something == anything) { throw new CustomException(" custom text message"); } // if(something == anything) { throw new CustomException(" custom text message"); } if(something == anything) { throw new CustomException(" custom text message"); }

you can try this 你可以试试这个

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? 另请参阅C# - Assert()方法有何功能? Is it still useful? 它还有用吗? and http://en.csharp-online.net/Assert . http://en.csharp-online.net/Assert

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM