chapter ten

10 Exceptions and Resources

 

This chapter covers:

  • Downsides to exception usage
  • Benefits of good exception usage
  • The relationship between resource handling and exceptions
  • Building an exception hierarchy for precise control

The topic of exceptions has proponents and detractors across the entire spectrum, advocating from rarely, if ever, to using them all the way to using them frequently. Over the years, several authors have published articles arguing for various positions between these. Many of these arguments are relevant, yet they mesh poorly with other viewpoints. This situation leaves us in a quandary of approaching exception usage. Many of the positions are correct but incomplete. There are numerous situations where one policy is meaningful but would make little sense in others.

Exceptions need to be considered in the scope of the entire program. A policy that addresses the behavior of a function may not be meaningfully extended to larger units. Many current programs running in production need to have the luxury of redesigning to handle a unified strategy for exceptions. In these myriad cases, almost any design is better than none. Yet, integrating localized strategies into larger units may prove frustrating and error-prone.

10.1 Using Exceptions

10.1.1 Intermixed Control and Recovery Paths

10.1.2 Confusing Exception Handling with Normal Error Handling

10.1.3 Difficulty of Retrofitting Exception Handling

10.1.4 Ambiguous Values

10.1.5 Ambiguous Data Types

10.1.6 Enforcing Error Handling

10.1.7 Providing Recovery Handlers

10.1.8 Transformation of Failure Types

10.1.9 Separation of Concerns

10.1.10 Encouraging Upfront Design

10.2 Mistake #74 Not Throwing Exceptions from Constructors

10.3 Mistake #75 Throwing Exceptions from Destructors

10.4 Mistake #76 Allowing Resource Leaks When Using Exceptions

10.5 Mistake #77 Failing to Use the RAII Pattern

10.6 Mistake #78 Using Raw Pointers to Resources

10.7 Mistake #79 Mixing new and delete Forms

10.8 Mistake #80 Trusting Exception Specifications

10.9 Mistake #81 Failing to Throw by Value and Catch by Reference