An exception that occurs when a calculation attempts to divide a number by zero, which has an undefined result.
An exception that occurs when a calculation attempts to divide a number by zero, which has an undefined result.
This could occur as a result of many different actions, such as...
- You're using a variable which hasn't been initialised, or has a default value of zero
- The user has input a value which wasn't expected (such as text input to a numerical field), or the user entered a zero value
Your code should be able to prevent or handle this type of exception, if you're doing divisions that involve variable inputs...
- Detect - Before performing the calculation, check the value of the variables to ensure they aren't zero. If they are, perform an alternate operation, such as alerting the user of an error.
- Prevent - If the variable is being input from the user, restrict the users input to a range of values. For example, only allow numerical values to be entered, and numerical values should be >= 1. If the field can only accept a range of values like this, you can't end up with a zero in your calculation.
- Handle - Wrap your calculation in exception-handling code, such as a try-catch block. This will allow you to catch unexpected exceptions such as this, and perform an alternate operation, such as alerting the user of the error.