In defensive programming, the main idea is that if a routine is passed bad data, it will not be hurt, even if the bad dadta is another routine's fault.Three genreal ways to handle garbage in1. Check the values of all data from external sources.When getting data from a file, auser, the network, or some other external interface, check to be sure that the data falls within the allowable range.2. Check the values of all routine input parameters.3. Decide how to handle Bad INPUTS
AssertionWhen an assertion is true, that means everything is operation as expected When it's false, that means it has detected an unexpected error in the code.Guidelines for Using Assertions1 Use error handlng code for conditions you expect to occur;.. Use assertions for conditions that should never occur.Assertion check for conditions that should never occur. Error handling code check for off-nominal circumstances that might not occur very often, but that have been anticipated by the programmer who worte the code and that need to be handled by the production code.2. Avoid putting executable code in assertionsPutting code into an assertion raises the possiblity that the compiler will eliminate the code when you turn off the assertion.3. Use assertions to document perconditions and postconditionsPreconditions and postconditions are part of an approach to program Design and development Known as "design by contract" .hen precomonditions and postconditions areufactage, Each Routine or Class Fo RMS A Contract with the rest of the program.4. for highly robust code, assert, and then handle the error anyway.
Error Handling Techniques1. Return a neutral valueSometimes the best response to bad data is to continue operating and simply return a value that's known to be harmless.2. Substitute the next piece of valid data3. Return the same answer as the previous time.4. substitue the closest legal value.5. Log a warning message to a file.6. Return an error code7. call an error processing routine / object.8. Display an error message wherever the error is encountered.Exception1. Use exceptions to notify other parts of the program about errors that should not be ignored.2. Throw an exception only for conditions that are truly exceptional.3. Do not use an exception to pass the buckIf an error condition can be handled locally, handle it locally. Don 't throw an uncaught exception in a section of code if you can handle the error locally.4. Avoid throwing exception in constructors and desctructors unless you catch them in the same place.5. Throw exceptions at the right level of abstraction.P156. Include Al L information That LED to the Exception in The Exception Message.7. Know The Exceptions Your Library Code THROWS8. Consider Building A Centralized Exception Reporter.