Hand-apply f2851b7066d0e12102b0f3aabc2b827a261206a9 from master; replace all assert()s with thrown exceptions.