diff options
author | Paul Sokolovsky <pfalcon@users.sourceforge.net> | 2014-03-31 02:20:00 +0300 |
---|---|---|
committer | Paul Sokolovsky <pfalcon@users.sourceforge.net> | 2014-03-31 02:23:57 +0300 |
commit | 6ded55a61f6bbf007d518fc4531287de08fe51c4 (patch) | |
tree | f78ee04bd9636bea80d6b63d86f8044c76fdb17a | |
parent | 96ed213320cb627c1df7ea8550b86b0bba5cb559 (diff) | |
download | micropython-6ded55a61f6bbf007d518fc4531287de08fe51c4.tar.gz micropython-6ded55a61f6bbf007d518fc4531287de08fe51c4.zip |
py: Properly implement divide-by-zero handling.
"1/0" is sacred idiom, the shortest way to break program execution
(sys.exit() is too long).
-rw-r--r-- | py/runtime.c | 13 | ||||
-rw-r--r-- | tests/basics/float1.py | 13 | ||||
-rw-r--r-- | tests/basics/int-divzero.py | 9 |
3 files changed, 32 insertions, 3 deletions
diff --git a/py/runtime.c b/py/runtime.c index 4898864962..1eca454806 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -348,13 +348,20 @@ mp_obj_t mp_binary_op(int op, mp_obj_t lhs, mp_obj_t rhs) { } case MP_BINARY_OP_FLOOR_DIVIDE: case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE: - { + if (rhs_val == 0) { + goto zero_division; + } lhs_val = python_floor_divide(lhs_val, rhs_val); break; - } + #if MICROPY_ENABLE_FLOAT case MP_BINARY_OP_TRUE_DIVIDE: - case MP_BINARY_OP_INPLACE_TRUE_DIVIDE: return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val); + case MP_BINARY_OP_INPLACE_TRUE_DIVIDE: + if (rhs_val == 0) { +zero_division: + nlr_jump(mp_obj_new_exception_msg(&mp_type_ZeroDivisionError, "division by zero")); + } + return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val); #endif case MP_BINARY_OP_MODULO: diff --git a/tests/basics/float1.py b/tests/basics/float1.py index 200d955856..bf1305c3d5 100644 --- a/tests/basics/float1.py +++ b/tests/basics/float1.py @@ -1,3 +1,16 @@ # basic float x = 1 / 2 print(x) + +print(1.0 // 2) +print(2.0 // 2) + +try: + 1.0 / 0 +except ZeroDivisionError: + print("ZeroDivisionError") + +try: + 1.0 // 0 +except ZeroDivisionError: + print("ZeroDivisionError") diff --git a/tests/basics/int-divzero.py b/tests/basics/int-divzero.py new file mode 100644 index 0000000000..d1fc579321 --- /dev/null +++ b/tests/basics/int-divzero.py @@ -0,0 +1,9 @@ +try: + 1 / 0 +except ZeroDivisionError: + print("ZeroDivisionError") + +try: + 1 // 0 +except ZeroDivisionError: + print("ZeroDivisionError") |