Add some defensive checks before casting.