Exception Handling and Error Handling

Exception Handling and Error Handling

WHAT EVERY PROGRAMMER MUST KNOW ABOUT EXCEPTIONS RAVI SHARDA APRIL-2011 “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 • Whether or not it leads to failure is a function of: • 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 (cont…d) • 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 doesn‟t 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 exception handling and error handling Src: Hasan Sözer, “Architecting Fault-Tolerant Software Systems” ISBN 978-90-365-2788-0 exception handling and dependability Src: Hasan Sözer, “Architecting Fault-Tolerant Software Systems” 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 Tucker - Allen B. Tucker , “Programming Languages” , what is an exception condition? • When an object cannot fulfill a responsibility for some reason • When some piece of code can‟t continue on its expected path • 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 identifying points of failure • Failure modes: “In what ways could this subsystem or component fail?” • Effects of failure: “What effects would the failure have, as perceived by the customer?” • Wirfs-Brock: Focus on collaborations among • objects that interface to the user and the rest of the system • objects within the system and objects that interface with external systems • objects outside a neighborhood and objects inside a neighborhood • objects in different layers • objects at different abstraction levels • objects of your design and objects designed by someone else • your objects and objects that come from a vendor-provided library Rebecca Wirfs-Brock, “What It Really Takes to Handle Exceptional Conditions” error handling in older languages errorCodeType readFile { initialize errorCode = 0; open the file; • Conventions were used for if (theFileIsOpen) { languages that do not support determine the length of the file; if (gotTheFileLength) { throwing and catching allocate that much memory; exceptions if (gotEnoughMemory) { • Define a function that returns an read the file into memory; if (readFailed) { unusual or illegal value when a errorCode = -1; run-time failure occurs } } else { errorCode = -2; } } else { errorCode = -3; } … Src: Allen B. Tucker , “Programming Languages”. Example by JavaPassion.org exception handling in java readFile { Helps you in try { open the file; Separating error-Handling code from “regular” business determine its size; logic code allocate that much memory; read the file into memory; Propagating errors up the call close the file; stack } catch (fileOpenFailed) { Grouping and differentiating doSomething; error types } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { • Doesn't spare you the effort of doSomething; doing the work of detecting, } catch (readFailed) { reporting, and handling errors, doSomething; • But, they do help you in } catch (fileCloseFailed) { organizing the work more doSomething; effectively } } dealing with abnormal situations • Does your software really need to break easily in reaction to such failures? • Trip up immediately • Worse yet, fail in unpredictable ways • Exception handling == Dealing with abnormal situations Allows you to make your software robust and reliable • Robustness: A robust program always terminates in a defined way, so that behavior is predictable for all possible inputs. • These include protection against incorrect usage, degenerate inputs and all kinds of errors. • 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 make exceptions expressive • Name an exception after what went wrong, not who raised it • Why? Makes it easy to associate the situation with the appropriate action to take . If you name an exception after who threw it, it becomes less clear why the handler is performing the specific action try { authenticator.authenticate(userName, password); } catch (TooManyLoginAttemptsException(e)) { // handle too many login attempts } . Examples from Java API: . FileNotFoundException, EOFException, MalformedURLException, SQLIntegrityConstraintViolationException, SQLSyntaxErrorException Src: Rebecca Wirfs -Brock, “What It Really Takes to Handle Exceptional Conditions” homogenize exceptions • Convert/homogenize exceptions - at package/subsystem boundaries, or, for a related sets of exceptions • Why? • If you let checked exceptions propagate without much thinking, • you must have then all defined in your throws clause. • Callers have to handle and potentially throw them in turn to their callers • Anytime you change your method, the calling method and its callers in turn may need to change their throws clause • 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 homogenize exceptions (cont…d) . Examples from Java API: • IOException • Subclasses: CharacterCodingException, ClosedChannelException, EOFException, FileNotFoundException, HttpRetryException,MalformedURLException, UnsupportedEncodingException, UTFDataFormatException, etc. • Example from Hibernate • HibernateException • Subclasses: IdentifierGenerationException, LazyInitializationException, NonUniqueObjectException, TooManyRowsAffectedException, etc. • QueryException • QuerySyntaxException, QueryParameterException, etc. preserve encapsulation • Recast lower-level exceptions to higher-level ones whenever you raise an abstraction level • The exception‟s abstraction level should be consistent with the interface‟s abstraction Adapted from: McConnell, Steve. “Code Complete”, 2nd Edition. Microsoft Press. © 2004 preserve encapsulation (cont…d) • Why? • When low-level exceptions percolate up to a high-level handler, the handler has little context to make good exception handling decisions • To include the trace for the lower-level exception, you can use “chain exceptions” • Passing exceptions through different layers without abstraction will violate the principle of information hiding • It reduces reusability and clarity of the design • An exception thrown by an object‟s method is part of the interface • Therefore, • Throw UserPreferencesNotAvailableException from loadUserPreferences() • as opposed to an SQLException • Throw EmployeeDataNotAvailableException from Employee.getTaxId() • As opposed to an EOFException Adapted from: McConnell, Steve. “Code Complete”, 2nd Edition. Microsoft Press. © 2004 preserve encapsulation (cont…d) • Motivating example • Exceptions can occur at many levels of abstraction in a platform • At the hardware level, exceptions include illegal operations such as division by 0, illegal memory references such as segmentation faults and bus errors. • At the programming languages level, exceptions include those caused by events such as out-of-bounds array index, an attempt to read to value to the wrong type, or an attempt to access an object in the heap by using a null pointer. • The hardware and the programming language preserve encapsulation when they handle and propagate faults, leading to a clean separation

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    52 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us