Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The paradox of CantHappen is that if the programmer truly thought it can't happen then there would be no need for it in the first place. The only reason to include it is because of a fear that it may in fact happen.

Rust funny enough has unreachable()! for that case, but it also has unreachable_unchecked() for actually unreachable code. The latter has undefined behavior and exists to help the optimizer.



I’m guilting of writing a “can’t happen” branch (as I’m sure many of us are).

I stripped it out before production after verifying it couldn’t actually happen but it was something like an artefact of my thinking process while writing the code.

It feels like a kind of assertion of underlying assumptions, and I know enough to know I’m fallible.

I’m always careful to make the error message something reasonable if it ever did actually come up in a tech demo or something though. Anything else is tempting the Fates.


I don’t understand why the message would be ‘Can’t happen’ in the first place.

I’d always make it something like “If you see this, something entirely unexpected went wrong.”

Showing and triggering the error is helpful in itself since it’ll generate a trace and all the attendant stuff.


"lp0 on fire" and "PC LOAD LETTER" are two good ones, too.


What does unreachable()! do actually? I had no idea that was a thing.


It terminates the program with panic!

https://doc.rust-lang.org/std/macro.unreachable.html


So is the usual flow to throw these in places where code shouldn't execute but then create tests to try and trip it up to see if that is truly the case? I would hate to be running a release build with this, or does the compiler do something different depending on build type?


> I would hate to be running a release build with this

The usual argument is that the program would be in an invalid state if the condition was reached, so the only option is to crash. If it turns out it's a valid state, then the programmer can treat in a branch. I don't think tests would capture this because they would operating under the same assumption that such states cannot exist. Maybe fuzzy testing could surface an issue like this.


Rust has a few of those, they all panic but with different default messages: panic!(), todo!(), unimplemented!(), and unreachable!()




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: