Is there any reason to throw a DivideByZeroException?

Armstrongest picture Armstrongest · Apr 8, 2010 · Viewed 7.9k times · Source

Are there any cases when it's a good idea to throw errors that can be avoided?

I'm thinking specifically of the DivideByZeroException and ArgumentNullException

For example:

double numerator = 10;
double denominator = getDenominator();

if( denominator == 0 ){
   throw new DivideByZeroException("You can't divide by Zero!");
}

Are there any reasons for throwing an error like this?

NOTE: I'm not talking about catching these errors, but specifically in knowing if there are ever good reasons for throwing them.

JUST TO REITERATE:

I KNOW that in the example I gave you'd probably be better off handling the error. Perhaps the question should be rephrased. Are there any reasons to throw one of these errors instead of handling it at this location.

Answer

juharr picture juharr · Apr 8, 2010

Let's say you write a library to work with really big integers that don't fit into Int64, then you might want to throw DivideByZeroException for the division algorithm you write.