You have a clamped inductive load and what is known as the inductive kickback voltage is what is being clamped.
Consider the current in the inductor with the transistor on at some time \$t_0\$ with a current \$I_0\$.
Now turn the transistor off, remembering it will not be instantaneous. The current will go from \$I_0\$ to zero in some time \$t_x\$.
As the current is decreasing, we have a change in current of \$ -\frac {\delta I} {\delta t}\$ (which is really more accurate in this case assuming a linear rate of change of current).
Merging our current against the standard equation for inductive kick, the voltage across this inductor is therefore \$ (-)(-)\ L\frac {\delta I} {\delta t}\$; this is an important point - the voltage at the collector of the transistor (if not clamped) can reach enormous potentials.
If I take a load current of a modest 50mA and a switching time of 20 nsec (not at all uncommon), with an inductor of 20μH then the collector voltage would go to 62V, given by the inductive kick plus the 12V supply (and probably more as the true instantaneous rate of change may well be faster at some point during the current decay).
This would destroy a 40V part; the diode clamps the collector at no more than Vcc + a diode drop (about 12.7V) and forms a circulating current loop for the decay current when the switch is turned off.
It can be informative to see the test circuit for an unclamped inductive load (often specified for MOSFETS):
Here, a clamping action is achieved by the internal avalanche diode inherent within the MOSFET.