First, do not panic. Locals almost everywhere distinguish between a foreigner making an honest mistake and someone being deliberately disrespectful, and a genuine apology fixes the vast majority of situations instantly.
The moment you realize the mistake, or someone points it out, acknowledge it simply: apologize, correct the behavior if possible, and thank the person who told you. Removing your shoes late, covering your shoulders with a borrowed scarf, or switching hands when eating are all easy corrections. A smile and a phrase like sorry, I am still learning your customs, works wonders in any language. Getting defensive or laughing it off dismissively is what actually causes offence.
Afterwards, treat it as free education. Ask someone you trust, a colleague, host or guide, what the correct practice is and why, since people generally love explaining their culture to a genuinely curious visitor. If the slip was serious, for example at a religious ceremony or in someone's home, a brief follow-up apology or a small gesture of thanks to the host repairs things gracefully.