Alex Rivera | Logout

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

Asked 2008-12-03T00:45:35.310
59

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

Edit
Report

1 Answer

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"));
answered 2008-12-03T01:21:42.850

Your Answer