Some languages have built-in affordances for those circumstances. In some statically typed languages, you can say that null and undefined are illegal values, and let your programming language throw a TypeError at compile time, but even in those languages, that can’t prevent null inputs from flowing into the program at runtime.
To get a better handle on this problem, we need to understand where these values can come from. Here are some of the most common sources:
Functions which could return nothing