57

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

Ben Griswold
  • 17,793
  • 14
  • 58
  • 60
  • 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. Thanks again for the feedback and sorry if the question was vague. – Ben Griswold Jul 27 '13 at 17:34
  • 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. – Ben Griswold Jul 27 '13 at 17:35

12 Answers12

79
try
{
  throw new DivideByZeroException();
}
catch (DivideByZeroException ex)
{
  LogHelper.Error("TEST EXCEPTION", ex);
}
GalacticCowboy
  • 11,663
  • 2
  • 41
  • 66
  • 2
    This is somewhat dangerous. The CLR will behave differently when a user explicitly raises an exception that is typically raised by the CLR. See this post for more details: http://blogs.msdn.com/jaredpar/archive/2008/10/22/when-can-you-catch-a-stackoverflowexception.aspx – JaredPar Dec 03 '08 at 01:05
  • However, a divide by zero exception is inherently testable and throwable without *actually* trying to perform the division. A stack overflow is a different beast, and is documented as such. Other exceptions also note "not intended to be thrown by client code"-type annotations. – GalacticCowboy Dec 03 '08 at 01:10
  • That is only for StackOverfloWExceptions. That is because many times, the catch clause would still be deep in the stack and overflow the stack itself. That exception can never be caught or handled when thrown by the CLR. – configurator Dec 03 '08 at 01:11
  • Or to restate a different way, just because the CLR *will* raise a certain exception doesn't mean I *shouldn't*. – GalacticCowboy Dec 03 '08 at 01:12
  • 1
    @JaredPar Your comment convinced me that there's nothing sure in programming and I feel like living in ignorance recursion. When I learn something I think I know it, but nooo, not so fast, there's always some exception of the rule. I'm getting tired of waiting for a moment when I'll be sure to know something for sure :( – dragan.stepanovic Jun 07 '12 at 14:26
  • @kobac i have about the same feeling. Every time I have a discussion about threading I a) learn something and b) realize that previous code I wrote is in fact wrong. It's disheartening at times. The lack of surety in programming is part of the reason software is fragile – JaredPar Jun 07 '12 at 18:19
44

Short answer:

throw new Exception("Test Exception");

You will need

using System;
Jesse Millikan
  • 3,104
  • 1
  • 21
  • 32
  • You shouldn't use Exception itself, you should either use an existing implementation or create your own. Exception is too generic. Brad Abrams (of the .NET framework design team) states that he wishes they could redo that class with a private constructor to avoid its use like this – Aaron Powell Dec 03 '08 at 02:00
  • This is good for testing a new audit log. Very basic that will break. worked for me, thanks. – JoshYates1980 Jan 09 '15 at 21:29
  • Logged in to vote for this. I am yet to see a good reason NOT to do it this way, especially for testing loggers. – VSO Jun 30 '15 at 22:29
5

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);
 }
Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
5
        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. "

Sunil Patil
  • 829
  • 8
  • 14
3

throw exceptionhere;

Isn't it?

Example I found was

        if (args.Length == 0)
        {
            throw new ArgumentException("A start-up parameter is required.");
        }
asleep
  • 4,054
  • 10
  • 34
  • 51
3

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 ?

James Curran
  • 101,701
  • 37
  • 181
  • 258
2

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.

Ben Griswold
  • 17,793
  • 14
  • 58
  • 60
1

throw new DivideByZeroException("some message"); ?

Or am I missing something?

Greg Beech
  • 133,383
  • 43
  • 204
  • 250
1

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"));
Collin K
  • 15,277
  • 1
  • 27
  • 22
1
public class CustomException: Exception
{
     public CustomException(string message)
        : base(message) { }

}

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

you can try this

0

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

yuriks
  • 1,084
  • 10
  • 13
0

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.

Community
  • 1
  • 1
Steve Pitchers
  • 7,088
  • 5
  • 41
  • 41