17 ms·
http://play.golang.org/p/TjzkjvDfYa http://play.golang.org/p/TjzkjvDfYa
by motter 13y ago
http://play.golang.org/p/TjzkjvDfYa http://play.golang.org/p/TjzkjvDfYa
- mostafah 13y agoFor people not familiar with Go Playground, that’s a compiler error.
- walrus 13y agoAnd here's what it looks like at runtime: http://play.golang.org/p/bVh52aKvMi http://play.golang.org/p/bVh52aKvMi
- Dewie 13y agoDoes it only throw a compiler error if you use 0 as a constant? Let's say you have a function that returns an int; does it force you to check if that int is non-zero before using it in division?
- chimeracoder 13y agoIt can only throw a compiler error if you use a 0 literal (or constant), because it cannot determine the runtime value of a variable denominator at compile-time (obviously). It does not force you to check, but if you wanted to "catch" the "exception" (really, "recover from the panic"), here's how you would do that. Note that this is admittedly a somewhat unidiomatic use of recover(): http://play.golang.org/p/dAQ01dus9Y http://play.golang.org/p/dAQ01dus9Y
- millstone 13y agoWhich applies not just to integer math, but also to floating point: http://play.golang.org/p/vEmiqUyPag http://play.golang.org/p/vEmiqUyPag Division by zero in floating point is well defined and useful, and does not produce a runtime exception. So why is this a compile time error? Edit And it produces the wrong result for division by negative zero: http://play.golang.org/p/DKoVG0Vlaf http://play.golang.org/p/DKoVG0Vlaf It should be -Inf, not +Inf. Go's floating point math is whack.
- pixie_ 13y agoIs there any way to 'catch' a divide by zero panic in go?
- Queue29 13y agoSure, http://play.golang.org/p/dAQ01dus9Y http://play.golang.org/p/dAQ01dus9Y
- chimeracoder 13y agoFor others: note that that's only because Queue29 assigned 0 to a variable before using it as the denominator, so there's no way for Go to catch that at compile-time. If you divide by a literal 0, this is a compile-time error, so there's no panic (and no need to recover()): http://play.golang.org/p/E0jSDAHwtg http://play.golang.org/p/E0jSDAHwtg
- pixie_ 13y agoInteresting thanks. Of course then I was wondering what this recover() stuff was and I found an explanation here - http://blog.golang.org/defer-panic-and-recover http://blog.golang.org/defer-panic-and-recover cool stuff.