Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Dividing By Zero not crash in Dart?

Tags:

flutter

dart

I think that the following code should crash because I am performing an integer division by zero:

int n = 42;
eatCake(n / 0);

Why does dividing by zero not crash my app?

like image 967
creativecreatorormaybenot Avatar asked Sep 05 '25 03:09

creativecreatorormaybenot


1 Answers

The key here is that n / 0 is not integer division.

Dart automatically performs double division and the double type has the double.infinity constant. This means that print(n / 0) will yield Infinity.
Furthermore, double.infinity is actually defined as 1.0 / 0.0.

If you use integer division instead, you will receive an IntegerDivisionByZeroException:

print(n ~/ 0); // <- IntegerDivisionByZeroException
like image 138
creativecreatorormaybenot Avatar answered Sep 08 '25 00:09

creativecreatorormaybenot