TO ERR IS HUMAN Wrote by Kim young-hyun (40) Dealing with the Inevitable – Error Conditions in...

21
TO ERR IS HUMAN Wrote by Kim young-hyun (4 0) Dealing with the Inevitable – Error Conditions in Code

Transcript of TO ERR IS HUMAN Wrote by Kim young-hyun (40) Dealing with the Inevitable – Error Conditions in...

TO ERR IS HUMAN

Wrote by Kim young-hyun (40)

Dealing with the Inevitable – Error Conditions in Code

In this chapter;

• The types of errors we encounter.

• Dealing with errors correctly.

• How to raise errors.

• Learning to program in the face of uncertainty.

From Whence It From

> Error category

• User error

• Program error

• Exceptional circumstances

Error-Reporting Mechanisms

- The several common strategies for propagating error. Each machanism has different localtity of error. (time, space) – reduce the locality of error to make it easier to see what going on (e.g., error code)

- The architect might consider it important to define ahomogeneous hierarchy of exception classes or a central list of shared reason codes to unify error-handling code.

Error-Reporting Mechanisms• No Reporting - The simplest error-reporting mechanism is don’t bother. An alterna

tive to ignoring error is to instantly abort program upon encounter encountering a problem.

• Return Values - A more advanced approach enumerates all the possible exit status

es and return a corresponding reason code. - If count() walks down a linked list and how to return the number of elements, there are three approaches

1. Return a compound data type(or tuple) containing both the return value and an error code. 2. Pass the error code back through a function parameter. 3. Atlernately, reserve a range of return values to signify failure. The count example can nominate all negative numbers as error reason codes.

Error-Reporting Mechanisms

• Error Status Variables

• - The function sets a shared global variable. After calling the function, you must then inspect this status variable to find out whether or not it completed successfully.

• - Ex. C standard library employee this technique with its errno variable. • => However, errors signaled through a sparate channel are much easier to

miss or willfully ignore. A shared global variable also has nasty thread safety implecations.

Error-Reporting Mechanisms• Exception (throw, try/catch) - When your code encouters a problem that it can’t handle, it stops dead and

throws up an exception – the language run time then automatically steps back up the call stack until it find some exception-handling code.

- Two operation models 1. The termination model – C++, .NET, and java 2. The resumption model

- Exception cannot be ignored. If it isn’t caught and handled, it will propagate to the very top of call stack and will usually stop the program dead in its tracks. You must take care to write exception-safe code.

- Exception cost – not free, their expense is justified compared to the cost of not doing any error handling.

Error-Reporting Mechanisms

- Whistle-stop tour of Exception safty : The level of Exceptional safty are described in terms of guarantee

s to the calling code.

• Basic guarantee

• Strong guarantee

• Nothrow guarantee

Error-Reporting Mechanisms

• Signal

- signal largly used for errors sent by the execution environment to the running program. (Like H/W interrupt, example; floating point exception)

- Your program could receive a signal at any time, and the code must be able to cope with this. When signal handler completes, program execution continues at the point it was interrupted. (Unix concept, now most platform)

- OS provide default handler for each signal, you can override these with your own handler.

Detecting Errors• Return values

- You determine whether a function failed by looking at its return code.

• Error status variables- You must inspect the error status variable. (C => errrno)

• Exceptions- You can choose to catch and handle it or to ignore it and let the exception flow up a level. You’ll only know what kind of exceptions might be thrown.(in java, exception specification for every method)

• Signals-There’s two way (1) install a signal handler (2) accept default behavior

Handling Error• Where it came from

• What you were trying to do

• Why it went wrong

• When it happended

• The severity of the error

• How to fix it

Handling Error (cont1)• When to Deal With Error

1) as soon as possible - This is self-documenting code technique, Managing each error near its source means that control passes through less code in an invalid state.

- This is best option for function that return error codes.

2) as late as possible - This recognizes that code detecting an error rarely knows what

to do about it. - Exceptions are ideal for this, it’s nice to separate “business logic” from error handling. - You know where to look for it and you can put the abort/continue policy in one place rather than scatter it through many functions.

Handling Error (cont2)

• Possible Reactions1. Logging - The log exists to record insteresting events in the life of the program, all error you encounter should be detailed in the program log. - Developer can investigate the error log, developer can do after logging.

2. Reporting - Don’t report when you encounter a recoverable situation. - It is good practice to report the problem immediately, in order to allow the user the best chance to resolve the situation or else decide how to continue. - this kind of reporting depends on whether or not the the program is

interactive.

Handling Error (cont3)• Possible Reactions

3. Recovery - If your code encounter an error and doesn’t know what to do about it, pass the error upward. It’s more than likely your caller will have the

ability to recover.

4. Ignore - You can write code that allows you to do nothing when an error crops up. But if you adopt this approach, you must it obvious in the code.

5. Prepagate - Return to upward the same reason code or propagate exceptions, you’ve got. - Return to upward the different reason code or catch and wrap up

exceptions, reinterpretet a more meaningful message.

Handling Error (cont4)• Code Implicationvoid nastyErrorHandling(){ if (operationOne()) { if (operationTwo()) { if (operationThree()) { … do more … } } }}

void flattenedErrorHandling(){ bool ok = operationOne(); If (ok) ok = operationTwo(); if (ok) ok = operationThree() if (ok) .. do more … if (!ok) { …clearn up after errors … }}

void shortCircuitErrorHandling(){ if (!operationOne()) return; … do somethng … if (!operationTwo()) return; … do something .. if (!operationThree()) return; … do something … }

void gotoHell(){ if (!operationOne()) goto error; … do something … if (!operationTwo()) goto error; … do something … if (!operationThree()) goto error; … do something … return;error: … clean up after errors … }

void ExceptionalHandling(){ try { operationOne(); operationTwo(); operationThree(); } catch( … ) { .. Cleanup after errros … }}

1 2 3

4 5

Crafting Error Message• Users don’t think like programmers, so present information the

way they’d expect.

• Make sure your messages aren’t too cryptic.

• Don’t present meaningless error code.

• Distinguish dire errors from mere warnings.

• Only ask a question if the user fully understands the ramifications of each choice. (continue? Yes : No)

Raising Hell• When writing a function, a erroneous things will happen that you’ll need to si

gnal to your caller. It must be report and use reporting mechanism.(C++, java => exception, C++)

• How you determine these errros is your own business, but when reporting them, consider the following:1. Have you cleaned up appropriately first? 2. Don’t leak inappropriate information to the outside world in your error reports.3. Use Exceptions correctly. 4. Consider using assertions 5. If you can pull forward any tests to compile time, then do so. 6. Make it hard for people to ignore your errors.

Raising Hell(cont)• Here’s a checklist of the general kind of error checks you

should make in each function: - Check all function parameter.- Check that invariants are satisfied at interesting points in execution.- Check all values from external sources for validity before youuse them. - Check the return status of all system and other subordinate function calls.

AN EXCEPTION TO THE RULE - Don’t use the exception to break a while loop or end recursion by throwing exception.

- Follow the idioms of your language, and don’t write cute code for he sake of it.

Managing Errors• There are general considerations for managing the occurrence,

detection, and handling of program errors:

1. Avoid thing that could cause errors.

2. Define the program or routine’s expected behavior under abnormal circumstances.

3. Clearly define which components are responsible for handling which errors.

4. Check your programming practice: Don’t put it off until later.

5. When trapping an error, have you found a symptom or a cause? Consider whether you found problem here or a symptom of an earlier

problem. Put that in a more appropriate (earlier) error handler.

• Good programmer

- Combine their good intentions with good coding practices

- Write the error-handling codeas they write the main code

- Are thorough in the code they write, covering every error possiblility

• Bad programmer

- Take a harzard approach to writing code, with neither thought to nor review of what they’re doing

- Ignore the errors that arise as they write code

- End up conducing lengthy debugging sessions to track down program crashes, because they never considered error conditions in the first place

• Question & Answer