Don't live in fear of foreclosure, but do plan ahead. Even before you take out a loan, you can take steps to help ensure that you won't face foreclosure decades down the road.
First of all, practice wise financial habits and don't take out a loan you can't afford. Force yourself to live on a budget and don't fall into debt. If you don't pay attention to where your money goes, you will spend thousands of dollars that could go toward repaying your home loan on superfluous items. Spend 1/4 to 1/3 of your income on housing, but don't take out a loan based on the best-case income; instead, realize that you may lose a job or get sick or have a car break down. Purchase a house you can afford based on your current income, not your future income.
Next, make sure you carefully read and understand your mortgage before you sign it. Don't be afraid to ask questions; mortgages can be very confusing documents. In particular, make sure you understand the sections on default or foreclosure and that you keep multiple copies of your mortgage.
After you take out your loan, get in the habit of making your payments on time. Your lender cannot foreclose as long as you stay current on your payment plan, so make sure you know exactly when and where your payments are due and how much you owe. Making your payments is the foolproof way to avoid foreclosure.
Finally, maintain a good relationship with your lender. Many mortgages are transferred between lenders, but as much as possible, have a person you can contact with questions regarding your mortgage. Get to know that person before you ever have financial difficulties, for the better that person knows you, the more willing he will be to help you out of financial trouble. If you have financial trouble, contact your lender immediately to discuss how your situation will affect your payments, and above all, never avoid notices from your lender. Foreclosure is a costly hassle for banks, and they want to help you catch up, but if they never hear from you and/or you seem antagonistic, they will not hesitate to take that route.