Ben Griswold Ben Griswold - 12 days ago 5
C# Question

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

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