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.
DivideByZeroException is a class that handles errors generated from dividing a dividend with zero.
Trying to divide an integer or Decimal number by zero throws a DivideByZeroException exception. To prevent the exception, ensure that the denominator in a division operation with integer or Decimal values is non-zero.
The "Divide-by-zero" exception is for dividing by zero with the div instruction.
CSharp Online TrainingDivide by zero is the System. DivideByZeroException, which is a class that handles errors generated from dividing a dividend with zero.
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.
The .NET runtime is already very good at throwing these exceptions. They are also highly descriptive of what is wrong, you can't add any good commentary to the exception message. "You can't divide by zero" adds no value.
However, you can avoid many of these exceptions by screening the values passed by the client code. You'll want ArgumentNullException with the name of argument if the client code passed a null, ArgumentException when it passed something that is liable to trip DivideByZero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With