The nerve in a tooth can become infected for many reasons. An area of deep decay could involve the nerve, or the accidental fracture of the tooth could expose the nerve. Sometimes, just a blow to the tooth can cause the nerve to die and become infected.
In any case, when the nerve becomes infected, the nerve tissue must be removed by either extracting the tooth, or performing a root canal (endodontic treatment).
Ideally, the root canal should be done before the infection has a chance to get into the bone, and the area develops extreme swelling and pain.
Periodic dental examinations, and having your tooth checked when it first begins to hurt will usually help avoid severe complications.