Basically Fleeting Frames' advice.
- Seal yourself in (and use a civilian alert burrow).
- Prepare a trap either for capture or kill. Kill might be hard, although cave-ins, obsidian casting, and repeating menacing spikes are good methods. Keeping it contained and letting it out to get killed by a goblin siege is an alternative (it will probably kill one or two goblins in the process).
- Open up so the Titan can reach the trap.
I generally make my fortresses with 4 access tunnels (only one is wide enough for wagons), each of which has a raising drawbridge at each end, plus a door at the inner side (there are cage traps in them as well, but those are useless against titans). With such a construction, open both the outer and inner drawbridges to allow the Titan to path to the fortress. Once it is inside the tunnel, order both drawbridges to be closed NOW!.
When the Titan nears the door, lock it (I don't think it matters). The door both serves as a target for its building destroying, as well as a means to delay it until the drawbridges get closed. If you don't have any repeating menacing spikes set up, you can either engineer a cave-in of the whole tunnel, or keep it locked in until the next siege.
If you hadn't prepared for attack, you can still dig your tunnel, but leave the ramp to the surface undug, build the drawbridges and the door, and then let a miner dig the last bit to the surface and then try to run for it. The miner may have to be sacrificed, however, unless you time it so that the Titan is chasing wildlife at the opposite end of the surface when you do it.