You need to verify that your object or thing you're using in your code is in a valid state before you use it.
See All 9 Episodes of "Shit Code"