C# - Is it possible to make divide-by-zeros return a number, instead of throwing an exception?
I have an expr开发者_JAVA技巧ession that includes divisions, for which some of the denominators are sometimes zero. However, in those cases I would like that division to result in 1, instead of throwing an exception. Is there any straightforward way about doing this, or am I forced to do some if statements and changing the inputs to the expression to get this desired effect?
Although I must question the motives here, if you need to do it, make a function.
double SafeDiv(double num, double denom) {
if(denom == 0) {
return 1;
}
return num/denom;
}
You could write a function for dividing. Here's an extension sample idea:
public static float DivideBy(this float toBeDivided, float divideBy){
try
{
return toBeDivided / divideBy;
}
catch(DivideByZeroException)
{
return 1.0;
}
}
Since it is not possible to redefine the division operator for built in types, you need to implement your version of division in a function.
Something like this?
public T divide<T>(T dividend, T divisor) {
return ((divisor == 0) ? (1) : (dividend / divisor));
}
or perhaps...
public T divide<T>(T dividend, T divisor) {
try {
return dividend / divisor;
}
catch (DivideByZeroException) {
return 1;
}
}
Personally, if you know that the divisor may be 0 in some cases, I wouldn't consider that case "exceptional" and thus use the first approach (which can also, quite conveniently, be inlined manually if you are so inclined).
That said, I agree with what Chris Marasti-Georg wrote, and question the motives for doing this.
No. If I understand your question, you would like to change the behavior of the divide operation and have it return 1 instead of throw. There is no way to do that.
Check for the denominator first if not equal to zero perform the operation
public double ReturnValueFunction(int denominator, int numerator)
{
try
{
if(denominator!=0)
{
return numerator/ denominator;
/* or your code */
}
else
{
/*your code*/
return someDecimalnumber;
}
}
catch(Exception ex)
{
}
}
If either divider or divisor are double and divisor is 0 (or 0.0) result is positive or negative infinity. It will pass through all subsequent operations without throwing, and instead returning ±Infinity or NaN, depending on the other operand. Later you can check if final value is something meaningful.
If it is for some reason necessary to return 1 when dividing by zero, then you have several options:
- Custom generic function
- Custom type with overloaded operators
- Check if divisor is 0 before the division
This is not something that is usually done, as far as I know, so you might rethink why would you do that..
Maybe you could try this
double res = a / (b == 0 ? a : b);
精彩评论