Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to throw a DivideByZeroException?

Tags:

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.

like image 704
Armstrongest Avatar asked Apr 08 '10 15:04

Armstrongest


People also ask

What is DivideByZeroException?

DivideByZeroException is a class that handles errors generated from dividing a dividend with zero.

How to avoid Divide by zero error c#?

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.

What exception is raised if you attempt to Divide by zero with either div or idiv?

The "Divide-by-zero" exception is for dividing by zero with the div instruction.

Can you Divide by 0 in c#?

CSharp Online TrainingDivide by zero is the System. DivideByZeroException, which is a class that handles errors generated from dividing a dividend with zero.


2 Answers

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.

like image 97
juharr Avatar answered Oct 24 '22 18:10

juharr


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.

like image 40
Hans Passant Avatar answered Oct 24 '22 20:10

Hans Passant