简体   繁体   中英

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. I've always chosen to raise a DivideByZeroException using an approach similar to the following code snippet:

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#?

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; 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 ?

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.

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.

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

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? Is it still useful? and http://en.csharp-online.net/Assert .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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