Most people have trouble estimating projects, especially when they are new. When estimating, we tend to think of the project on a very high level and fail to take into account the details involved in figuring a good target estimate.
The most logical solution is to prevent this problem by focusing on improving your estimation techniques:
Break down the work into small subtasks:
To create a good estimate, first break down the project into high level sections that you know will be part of the project. If you're working on a website with a front-end and a back-end, for instance, then you know you have a client-side front-end portion and a server-side backend.
For instance, I would break down the front-end by pages, then break each page down by component, then break the components down into work that needs to be done on the front-end and work that would need to be done to populate that front-end with any data. I'd then gather an estimate of how much time it would take to complete those components.
Once completed, I'd look at my spreadsheet. Any tasks that take longer than a day, I revisit and break them down even further. Ideally, I try to break down each task into subtasks where each subtask takes about an hour or two.
By breaking down tasks into subtasks that are measured in just a few hours, I most likely uncover additional details and scope that I would otherwise overlook had I just used my initial gut feeling.
Lastly, add an additional 30% for bugs and other problems that may occur, just in case.
What if I still have a problem with underestimating:
As soon as you think you might go over your budget, tell your client immediately. If it's still early, you may be able to clarify the scope and negotiate a higher rate on the contract. Explain to the client what part of the project scope you overlooked, and offer to bill for the additional time at a lower rate.
If they refuse, then you can decide whether or not the time you've already invested is worth writing off, and if it's worth losing the client. In cases where there would be a huge hardship, you may just want to terminate the project.
However, if you know there's going to be more work, or if you know you won't go over your budget by too much, it may be wise to just simply eat the losses, knowing that you'll have more work later and an opportunity to learn from the mistake.
No matter what, it's still important to explain that you may have underestimated so that the client isn't surprised by higher estimates later on.