Ya, kind of a pain. Here's an article to help understand this https://www.healthline.com/health/mens-health/random-erections
It's actually normal, albeit inconvenient. How old are you? It's more common in teens and young men. Is this a new thing or been going on for awhile? It can be a normal part of development. If it happens, the best thing to do is try not to think about it. Just do whatever else it is you are doing and focus on that than the erection. It can be embarrassing when you are with others, so just discreetly keep it hidden but you aren't alone. Many guys have this happen and it gets better as you get older.