The computers in a car are constantly monitoring the operating conditions and sensors that are in the car. When a test fails or something goes out of a pre specified range a DTC is set.
The biggest misconception about a DTC is that it tells you what to replace, it does not. A DTC tells you what test failed or what parameter went out of range. This identifies the where something failed but not why. It drives me insane when parts stores read codes and give you parts to replace. Their job is to sell you parts not diagnose cars. For example P0401 EGR flow insufficient is a common code. The knee jerk reaction tends to be to replace the EGR valve. A more common failure is when the EGR passages plug up causing the insufficient flow. All the EGR valves in the world won't fix plugged up passages.
There are two basic routes for diagnosing codes. The first is the manufacturer service manual. The service manual contains diagnostic routines for every code that the vehicle can set. These diagnostic routines give step by step instructions on what to check and how. These manual can be found on line or bought. Service facilities have subscriptions to websites like Alldata, Mitchel and Identifix which are repositories for all manufacturer service manuals. Unfortunately the average person can't afford these websites. When diagnosing a code that you're not familiar with this is always the first stop. Following these diagnostic routines will find the exact problem 99% of the time. The problem is that 1% where something goes wrong that the engineers who wrote the diagnostic routines could not account for.
This brings us to the second way. This method involves raw experience. After you do this for a while, you find certain patterns in failures. This allows you to jump to a specific test without going through the entire diagnostic routine. This is also where that 1% falls. For example P0402 EGR flow excessive, or EGR flow during non EGR condition. This code is commonly caused by a plugged up catalytic converter. Older diagnostic routines did not include checking this as a procedure. Later as it was found out that this is a problem this step was added to newer manuals. (Once a manual is printed it is effectively set in stone, they won't reprint another one to update it.)