Many people who are facing foreclosure are considering bankruptcy, and vice-versa. This is because people who lose their homes to foreclosure typically have financial hardships and other difficulties that also result in problems elsewhere, like with credit card debit, student loans, back taxes, or other issues.
This is why many people like yourself ask about bankruptcy when they are facing the prospect of losing their home. The question can best be answered by referring you to a bankruptcy attorney, but in general, you do not necessarily have to file for bankruptcy if you go through a foreclosure.
There are situations in which you might, though. If you want to try and keep your home, then you could entertain the possibility of Chapter 13 bankruptcy. This is for people with regular sources of income who need time and a little help to reorganize and pay off their debts. Usually, Chapter 13 allows you to keep your home and work off the debts you have incurred. This helps particularly if your home is the only source of problematic debt on your record.
If you cannot go through Chapter 13, it may or may not be a good idea to pursue Chapter 7 bankruptcy (the most common type). This is because a Chapter 7 bankruptcy will stay on your record for 10 years. A foreclosure, by contrast, stays on your record for 7 years. Therefore, generally speaking, if you have multiple financial burdens, a Chapter 7 bankruptcy accompanied by a foreclosure may be your best bet to get a clean slate (minus the debts that are not dischargeable, like student loans, alimony/child support, and property taxes).
Again, consulting with a bankruptcy attorney in the end is always best.