Transaction Out of Gas Error: Why It Happens and How to Avoid It

In short
An out of gas error means the work needed more gas than your limit allowed. Why it happens, why the whole fee is spent, and how to avoid it next time.
A transaction out of gas error means the network started your job, worked through it, and hit the ceiling you set before it finished. Everything it had done was undone, your coins stayed where they were, and the entire fee was spent. This is the most expensive way for a transaction to fail, which is exactly why it is worth understanding once.
Why is the money gone if nothing happened?
Because the work was real. Thousands of machines ran your instruction step by step, and they are paid for the steps they ran whether or not the last one was reached. Picture paying a taxi driver for ten kilometres and then asking for twelve: the driver stops at ten, you walk the rest, and the fare you already handed over is not coming back. A contract that refuses you on purpose is kinder — unused gas is returned — but running out is the version where the ceiling itself is consumed.
Why did the estimate turn out to be wrong?
Your wallet guesses the cost by rehearsing the transaction against the blockchain as it looks right now. By the time your turn arrives, the blockchain has moved. A mint that was half finished is now nearly sold out and the contract takes a longer path. A token that charges a fee of its own adds steps nobody counted. An Aave position that was simple a minute ago now touches more of the contract. The guess was honest; the world changed under it. The other frequent cause is a person: someone lowered the limit by hand to save money, which never works, because the limit is a ceiling on work and not a price.
How do you avoid it?
Accept the gas limit your wallet suggests, and leave a margin the first time you touch an unfamiliar contract — raising the ceiling costs nothing when it is not used, since you pay only for the work actually done. Avoid sending during the busiest minutes of a popular launch, when estimates age fastest. And if a transaction fails this way twice with the same settings, the problem is the settings, not luck.
A different error, "intrinsic gas too low", looks similar but is caught before anything runs and costs nothing: see what that one means. For where the fee itself ends up, see the money's path after a failed transaction.