In popular programming languages dividing by zero results in an exception being thrown such as ZeroDivisionError
in python. Does solidity allow for such exception handling? and if so how would I handle a division by zero?
1 Answer
Division by zero is an exception that will result in the transaction being reverted.
function foo(uint num, uint den) public pure returns(uint result) {
if(den == 0) return 0; // there is no "correct" result, so decide what to do
result = num / den;
}
There are other subtleties around division - no floats, precision, truncation - setting those aside to stick to the original question.
Generally, division by zero is a logic error or input error, so reverting the transaction is the correct thing to do. Since the default message is cryptic and meaningless to most users and even possibly the developers, you can raise a more informative message while still rejecting the transaction with:
function foo(uint num, uint den) public pure returns(uint result) {
require(den != 0, "denominator cannot be zero");
result = num / den;
}
Hope it helps.