Answer the question
In order to leave comments, you need to log in
DivideByZeroException(). Why is it needed?
What is the advantage of DivideByZeroException() over a simple IF ? I can check with if for 0.
public double CalcFraction1 (double x, double y) {
var numerator = Math.Abs(x) - Math.Abs(y);
var denominator = (1 + Math.Abs(x) * Math.Abs(y));
if (denominator == 0) {
throw new DivideByZeroException();
}
return numerator / denominator;
Answer the question
In order to leave comments, you need to log in
https://msdn.microsoft.com/en-us/library/system.di...
Dividing a floating point value by zero does not throw an exception;
Well, you check for zero, and what will you return from the function? If zero, then it will be an invalid result.
Therefore, we check for zero manually and throw an exception, this is better than getting the wrong value.
If you do not throw an exception, then "Infinity" will be returned, do you need it? )
In short, code style.
You must adhere to the OOP paradigm and if you check with an IF condition that your division is not zero, then this is very bad programming.
Moreover, when using exception, you insert it into the try...catch logic and thus you can catch exceptions and, if necessary, pass them to the component that is responsible for this
I see no reason to check for zero if only an exception is thrown in the condition body.
The CLR will throw a DivideByZeroException without you if the denominator is zero.
Two examples:
1. a certain huge data set, according to which something is calculated
in the initial data, zero is unacceptable - an exception implying "everything is lost" and termination of actions (the wrong file is selected, etc.)
2. the same data set
in the process of complex calculations due to rounding, one of the divisors can be rounded to zero ... if it is predictable and permissible - you can branch with if-th and assign "pseudo-infinity" to the result of such division - for example, the maximum value of int, etc. and then continue the calculations
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question