A
A
Alexey FRZ2017-07-10 23:59:22
.NET
Alexey FRZ, 2017-07-10 23:59:22

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

5 answer(s)
A
aynur_safin, 2017-07-11
@leshqow

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

A
Anton, 2017-07-11
@MoonMaster

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

H
Howard Roark, 2017-07-11
@HowardRoark

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.

D
d-stream, 2017-07-11
@d-stream

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

M
Maxim, 2017-07-15
@Got_Oxidus

Throw an ArgumentException, it's clearer for the user of the function, because the consumer does not know what is inside the function, and this will confuse him.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question