My knowledge of real estate law is woefully inadequate to provide a definitive response, so be wary. With that said, let me expound further
With some exceptions for taxes and first mortgages, liens are paid off in the order they are recorded. Thus, a first mortgage has a higher priority than a second mortgage. If a house with no owner's equity and a $100,000 first mortgage is sold in foreclosure for $90,000 then any lien holders (second mortgage, homeowners association, contractors, etc.) receive nothing.
Because property taxes have a priority lien, most mortgage companies require escrow accounts so that they can assure that taxes are paid.
My understanding is that prior to a "sheriff's sale on the steps of the courthouse" a property in foreclosure is not technically "owned" by the lien holder. The property is in "receivership" by the court. Thus, the bank is not responsible for any utilities or homeowners association fees, etc.
Sometimes, a second mortgage holder will foreclose on a property. In such cases, a first mortgage holder will purchase the property at a lien sale in order to protect its investment. (However, even if the second mortgage holder forecloses, the first mortgage holder is paid off first to the extend funds are received.)
For the reasons above, this is why lawyers push homeowners associations to foreclose on unpaid assessments as soon as possible, before the first mortgage is in default. Otherwise, the association may not receive anything for back assessment in a foreclosure sale.
Most covenants have "provisions for the protection of first mortgage holders" included as boilerplate--and required by banks. Here is one I found quickly this morning:
Section 4. Liability for Unpaid Assessments. Any First Mortgagee who obtains title to or comes into possession of a Lot pursuant to the remedies provided in its First Mortgage or by foreclosure of the First Mortgage or by deed or assignment in lieu of foreclosure, and any purchaser at a foreclosure sale in connection with any such First Mortgage shall not be liable for the unpaid assessments of the Lot which were payable prior to the acquisition of title to or possession of such Lot by the First Mortgagee.
If banks come into possession due to foreclosure there are some state laws that exclude them from having to pay association fees. This is not true in all states. However, I do believe this is one of the huge problems right now in Florida.
I wish I was more informed about this, but my expertise is not in real estate law.
As an aside, I am going to propose next month that the legislature in Hoosierland consider changing the law to require banks and other holders of foreclosed homes to pay assessments from the time of possession. This may be a challenge, since it could galvanize the banks to oppose the entire bill.