There are two kinds of individual bankruptcies under the law. In a Chapter 7, you petition for protection from your creditors and surrender non-exempt assets to a trustee who then uses these assets to pay your creditors. In a Chapter 13, the trustee sets up a repayment plan and you pay a set monthly amount toward your outstanding debts. You keep all assets in a Chapter 13; there is no liquidation to satisfy creditors. In both scenarios, your 401(k) funds are safe under the Employee Retirement Income Security Act.
An exempt asset is something that a creditor may not seize, either through bankruptcy or a court judgment, to satisfy a debt. In accordance with the U.S. Bankruptcy Code, 401(k) funds are completely exempt from seizure (this also applies to other retirement accounts such as IRAs and Simplified Employee Pensions). If you are in a Chapter 13, the trustee will only require a payment from your disposable income into the repayment plan. You will not be forced to surrender any of your 401(k) money, but if you make any withdrawals from the 401(k), the trustee may require that the funds go toward repayment of creditors.
The law is not quite so cut-and-dried on 401(k) contributions. Each bankruptcy court can make its own rules on certain elective financial decisions, such as your voluntary contributions to a 401(k). Some courts will allow these contributions, some will not. Others will allow them under certain conditions; for example, you are nearing retirement or the contribution is of a reasonably small amount. If the contributions are mandatory as a condition of your employment, you have excellent grounds to have the court allow them.
Loans and Debts
If you take a loan from your 401(k), the bankruptcy court will consider that money available and non-exempt. A court trustee can either force repayment of the loan through liquidation of your other assets (Chapter 7) or consider the loan a "creditor" that must be repaid through your monthly repayment plan (Chapter 13). For this reason, it's a bad idea to borrow from a 401(k) to pay debts if you are considering bankruptcy, or to withdraw from any retirement account to provide yourself with a cash cushion while the bankruptcy is ongoing.