Check variables before using them

Fixes #2217