Beruflich Dokumente
Kultur Dokumente
What we anticipate seldom occurs; what we least expected generally happens. Benjamin Disraeli
slides overview
overview
designing exceptions using exceptions conclusion
slides overview
overview
designing exceptions using exceptions conclusion
terminology
Failure
A system fails when its behavior differs from that which was intended
With respect to intent, and not with respect to the specification
Error
An error is a system state that is liable to lead to a failure if not corrected
A fault in a software system may or may not cause an error
The redundancy in the system The system activity (the error may go away before it causes damage) what the user deems acceptable behavior. For instance, in data transmission there is the notion of acceptable error rate
Adapted from: Mario Barbacci et. al, Quality Attributes, CMU/SEI-95-TR-021, Dec. 1995 ISBN 978-90-365-2788-0
terminology (contd)
Fault
A fault is the adjudged or hypothesized cause of an error
May or may not cause an error For e.g., every exception thrown in your application doesnt lead to an error
Adapted from: Mario Barbacci et. al, Quality Attributes, CMU/SEI-95-TR-021, Dec. 1995 ISBN 978-90-365-2788-0
what is an exception?
Tucker
To throw an exception is to signal that the condition it represents has occurred To catch an exception means to transfer control to an exception handler, which defines the response that the program takes when the exception occurs
Venners
A structured way to perform a go-to from the place where an error occurs to the code that knows how to handle the error Forces client programmers (those who use your code by calling your methods) to deal with the possibility of an error condition encountered by your code
Common causes:
Users behaving incorrectly entering wrong information or failing to respond within a particular time Unavailable resources or requests to resources timing out Unauthorized requests Invalid requests such as malformed arguments Inconsistent state Dropped communications Bad data such as corrupt data, inconsistent data, missing files, etc. Coding or logic errors
Src: Allen B. Tucker , Programming Languages & Rebecca J. Wirfs-Brock, Toward Exception-Handling Best Practices and Patterns , Vol. 23, No. 5, September/October 2006, IEEE Computer Society
Reliability: The ability of a system to deliver its normal service in presence of errors and unexpected or incorrect usage (user errors).
Two aspects of reliability can be distinguished: Fault Tolerance and Robustness
slides overview
overview
designing exceptions using exception conclusion
homogenize exceptions
How?
Declare one exception class per logical subsystem, or for a related sets of exceptions
Applies to subsystem only, therefore, not in conflict with make expressions expressive
Have other exceptions derive from the subsystem base exception Callers can then name a single superclass in a catch block instead of all the individual exception classes for which a corrective action is appropriate
Src: http://c2.com/cgi/wiki?ExceptionPatterns
QueryException
QuerySyntaxException, QueryParameterException, etc.
preserve encapsulation
Recast lower-level exceptions to higher-level ones whenever you raise an abstraction level
The exceptions abstraction level should be consistent with the interfaces abstraction
Adapted from: McConnell, Steve. Code Complete, 2nd Edition. Microsoft Press. 2004
Passing exceptions through different layers without abstraction will violate the principle of information hiding
It reduces reusability and clarity of the design
Therefore,
Throw UserPreferencesNotAvailableException from loadUserPreferences()
as opposed to an SQLException
Adapted from: McConnell, Steve. Code Complete, 2nd Edition. Microsoft Press. 2004
The hardware and the programming language preserve encapsulation when they handle and propagate faults, leading to a clean separation of concerns during abnormal situations
Sometimes it may be simply impractical to map every error type to an exception class type. Define a general error type with an error code property.
For e.g., NoResponseFrom<ExternalSystemName>Exception mapping to time outs, b) unavailable, hung state, etc.
Adapted from: Klaus Renzel, Error Handling for Business Information Systems A Pattern Language, 2011
Complete: every possible exception checked or unchecked must be specified Precise: If the exceptions that can be propagated are organized in an inheritance hierarchy, all exceptions should be specified, not only the super type
2. 3.
make exceptions expressive and preserve encapsulation Use checked exceptions (often abstract exceptions)
Even if you omit checked exceptions for module-internal functions
Adapted from: Martin P. Robillard and Gail C. Murphy, Designing Robust Java Programs with Exceptions & Mayaleri ,et. Al
Unchecked exceptions
Not subject to compile-time checking for exception handling Built-in unchecked exception classes: Error, RuntimeException, and their subclasses Handling all these exceptions may make the program cluttered and may become a nuisance
Guarded suspension:
Suspend execution until conditions for correct execution are established, then try to perform the request
Provisional action:
Pretend to perform the request, but do not commit to it until success is guaranteed Makes sense when a request takes time and can be partially fulfilled in anticipation of it later completing it
Adapted from: Rebecca Wirfs-Brock, What It Really Takes to Handle Exceptional Conditions
Rollback:
Retry:
Adapted from: Rebecca Wirfs-Brock, What It Really Takes to Handle Exceptional Conditions
Src: Rebecca Wirfs-Brock et. al, Object Design: Roles, Responsibilities, and Collaborations, Addison Wesley, ISBN: 0-20137943-0, Nov 2002
Src: Rebecca Wirfs-Brock et. al, Object Design: Roles, Responsibilities, and Collaborations, Addison Wesley,
slides overview
overview
designing exceptions using exceptions conclusion
The message associated with each exception must specify (for a developer) in what way the parameter was invalid.
Parameter public class BankAccount { value is illegal public void withdraw(double amount) { if (amount < 0) { throw new IllegalArgumentException("Amount is negative"); } balance = balance - amount; } ... }
Another example:
You wouldnt want Excel to crash but it would be much worse if it ever produced an incorrect value in a spreadsheet that I use to manage my personal finances.
Adapted from: Nick Guerrera, FAQ: Why does FxCop warn against catch(Exception)?
Sloppy code
Tells your callers something can go wrong in my method Defeats the purpose of using checked exceptions
If the code throws other checked exceptions later, you wouldnt be warned to handle them
Having base exceptions serves some purposes (mostly for management of exceptions)
Common behavior such as serialization, etc.
However, its a design bug to have methods throw them as blanket declarations
The purpose of checked exceptions to provide specific information to the caller about exceptions that might be thrown in a method
The above practice undermines that purpose
The call stack is lost, since the cause exception is not chained. Also, the original exception object (along with its state) is lost.
The newly created higher level exception object will then maintain a reference to the underlying root cause exception If the higher level exception is called to print its stack trace, it will include the stack trace of the root exception as part of its own output
Either log the exception, or throw it, but never do both Why?
Logging and throwing results in multiple log messages for a single problem in the code, and makes life hell for the support engineer who is trying to dig through the logs
IllegalStateException
NullPointerException
Why?
What's most important to the exception handler is to identify the exception and to gain information that will aid it in making a more informed response
Src: Rebecca Wirfs-Brock et. al, Object Design: Roles, Responsibilities, and Collaborations, Addison Wesley, ISBN: 0-20137943-0, Nov 2002
With exceptions as objects, you have the power to encapsulate an unlimited variety of functionality specific to the problem. - http://www.churchillobjects.com/c/11012k.html
Why?
If you propagate an exception far away from the source, it can be difficult to trace the source Often objects further away from the problem cant make meaningful decisions.
Note: sometimes the most able object is one that has been explicitly designed to make decisions and control the action
Controllers are naturals for handling exceptions as well as directing the normal flow of events
In production, if the log level is set as INFO or an upper level, request and response will not be available in the logs
Usage
Assertions are to assure the correctness of the program (Internal consistency and validity checks)
For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light. This gives you more confidence to assure correctness of the program.
Usage
Post-conditions
The contract must always be obeyed whether assertions are enabled or disabled
Using assertions to check nonpublic methods precondition is ok.
private void setRefreshInterval(int interval) { // Confirm adherence to precondition in nonpublic method assert interval > 0 && interval <= 1000/MAX_REFRESH_RATE : interval; ... // Set the refresh interval }
summary
Exceptions design practices
make exceptions expressive homogenize exceptions preserve encapsulation mapping error codes to exception precisely and completely specify exceptions at module/subsystem boundaries Know when to use checked and unchecked exceptions strategies for handling abnormal situations describe your exception handling design
summary
Exceptions usage practices
validate inputs to your public interface do not try to handle coding errors do not catch or throw top-level exceptions do not throw exceptions from within finally favor the use of standard exceptions provide context along with an exception chain exceptions when translating an exception either log or throw but dont do both handle exceptions as close to the problem as you can log exceptions effectively use assertions to reaffirm assumptions
in closing
Why dont we handle exceptions and errors well? Common excuses:
Its extra work, and I have a deadline looming
imagine watching a doctor performing an open heart surgery on you he has a deadline! unexpected things always happen, unlike the expected. And they mostly happen in production!
I am just trying out something that works, and Ill take care of exceptional scenarios later !
later never comes
Error handling clutters up the flow of the code, making it harder to read, and harder to spot the normal flow of execution
dont want to use my head figuring out points of potential failure
in closing
Robert C. Martin (Uncle Bob): 97 Things Every Programmer Should Know
Professionals take responsibility for the code they write
They do not release code unless they know it works. They expect QA to find nothing because they dont release their code until theyve thoroughly tested it.
Of course, QA will find some problems, because no one is perfect.
Professionals do not tolerate big bug lists (tragedies of carelessness) Professionals do not make a mess
They take pride in their workmanship
references
[Howell_Techni ques] [Renzel_Error_ Handling] [WirfsBrock_Excepti ons] [Wiki_Exceptio ns] [ObjectArchite cts_Error_Han dling] [McCune_Exc eption_Antipatt erns] Charles Howell and Gary Veccellio, Advances in Exception Handling Techniques (Alexander Romanovsky, ed., Springer 2001 Klaus Renzel, Error Handling for Business Information Systems A Pattern Language, 2011 Rebecca J. Wirfs-Brock, Toward Exception-Handling Best Practices and Patterns, Vol. 23, No. 5, September/October 2006, IEEE Computer Society http://c2.com/cgi/wiki?ExceptionPatterns http://www.objectarchitects.de/arcus/cookbook/exhandling/index.htm
[McConnell_C ode_Complete ]
McConnell, Steve. "Chapter 8 - Defensive Programming". Code Complete, Second Edition. Microsoft Press. 2004. Books24x7. http://common.books24x7.com/book/id_10482/book.asp
References (contd)
[Msdn_Excepti on_Guidelines] [Msdn_Excepti on_Block] [Szer_Fault_t olerant] [Cushing_Rule s_Exceptions] Design Guidelines for Exceptions, http://msdn.microsoft.com/enus/library/ms229014(VS.80).aspx Exception Handling Application Block, http://msdn.microsoft.com/enus/library/ff648029.aspx Hasan Szer, Architecting Fault-Tolerant Software Systems ISBN 978-90-365-2788-0 Jim Cushing, Three Rules for Effective Exception Handling, http://today.java.net/pub/a/today/2003/12/04/exceptions.html