T1002281 class cast ex

Instead of doing an unsafe cast, an exception is thrown directly (or a conversion if possible).

Second commit contains cleanups.