Skip to content

Commit 6ded55a

Browse files
committed
py: Properly implement divide-by-zero handling.
"1/0" is sacred idiom, the shortest way to break program execution (sys.exit() is too long).
1 parent 96ed213 commit 6ded55a

3 files changed

Lines changed: 32 additions & 3 deletions

File tree

py/runtime.c

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -348,13 +348,20 @@ mp_obj_t mp_binary_op(int op, mp_obj_t lhs, mp_obj_t rhs) {
348348
}
349349
case MP_BINARY_OP_FLOOR_DIVIDE:
350350
case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
351-
{
351+
if (rhs_val == 0) {
352+
goto zero_division;
353+
}
352354
lhs_val = python_floor_divide(lhs_val, rhs_val);
353355
break;
354-
}
356+
355357
#if MICROPY_ENABLE_FLOAT
356358
case MP_BINARY_OP_TRUE_DIVIDE:
357-
case MP_BINARY_OP_INPLACE_TRUE_DIVIDE: return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
359+
case MP_BINARY_OP_INPLACE_TRUE_DIVIDE:
360+
if (rhs_val == 0) {
361+
zero_division:
362+
nlr_jump(mp_obj_new_exception_msg(&mp_type_ZeroDivisionError, "division by zero"));
363+
}
364+
return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
358365
#endif
359366

360367
case MP_BINARY_OP_MODULO:

tests/basics/float1.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
11
# basic float
22
x = 1 / 2
33
print(x)
4+
5+
print(1.0 // 2)
6+
print(2.0 // 2)
7+
8+
try:
9+
1.0 / 0
10+
except ZeroDivisionError:
11+
print("ZeroDivisionError")
12+
13+
try:
14+
1.0 // 0
15+
except ZeroDivisionError:
16+
print("ZeroDivisionError")

tests/basics/int-divzero.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
try:
2+
1 / 0
3+
except ZeroDivisionError:
4+
print("ZeroDivisionError")
5+
6+
try:
7+
1 // 0
8+
except ZeroDivisionError:
9+
print("ZeroDivisionError")

0 commit comments

Comments
 (0)