why do we gain weight when exercising

I've spent most of the last decade getting clear on some important and often overlooked facts about wellness as it relates to women and obesity. First, exercise alone yields all kinds of amazing results, but weight loss isn't one of them. Even the American College of Sports Medicine admits that exercise is an ineffective weight loss tool.

Second, our ability to get and stay well (and to enjoy the process) depends a lot on where and how we get our information about wellness (popular media tends to be a pretty weak source).

And third, it's the responsibility of fitness professionals like me to shift the conversation about weight, wellness and behavior away from nickel-and-dime, waste-of-time crap (like calorie-counting), and on to the stuff that actually matters, like teaching clients how to care for and about themselves deeply and consistently, day after day.
Weight gain can also be from muscle mass, especially if you are new to exercise.

Muscle weighs more than fat by volume, so even if your weight is increasing you could still be losing fat and gaining muscle.

Endurance sports generally don't cause muscle growth in experienced athletes, but people who are new to fitness may experience slight muscle growth in the beginning as their muscles develop from being challenged in new ways.

If resistance training is a part of your fitness routine, the gain may be seen as a sign of progress that means those hours of weight lifting are beginning to work. This is why the term weight loss can be misleading and the term fat loss is more accurate.