The criminal law allows necessity be used as a defense in trial when the defendant's actions are the result of natural forces. This defense can be contrasted against the duress defense, which can be used when the defendant's actions were the result of forceful human influence. Self defense often qualifies as a kind of necessity, since in this case it is the natural instinct to preserve oneself from harm that motivates the violence, rather than the coercion of another human being. (In fact, it's not a stretch to think of "self defense" as a subcategory of the necessity defense.) Another potential application of the necessity defense would be for a defendant who is accused of speeding, if he was speeding to the emergency room with a heart attack victim in the back seat.
Sometimes certain acts of necessity can be used as a defense when they are specifically included in the statute defining the crime. A good example of this, though it's no longer relevant after the Roe v. Wade ruling, was the law criminalizing abortion: written into this law was a provision that justified performing an abortion under the necessity of saving the mother's life.
On the whole, however, the scope of necessity as a defense is fairly limited. Most courts require the necessity to be extremely great in order to justify breaking the law, and some courts have even done away with the defense altogether. As a general rule, the necessity defense requires that the harm done by the defendant be less than the harm avoided. To borrow an example from self defense, the threat of violence from a man can almost certainly never justify that man's murder.