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, with developers advocating from using them rarely, if ever, to using them frequently. Over the years, several authors have published articles arguing for various positions along this spectrum. Many of these arguments are relevant, yet they mesh poorly with other viewpoints. This situation leaves us in a quandary when approaching exception usage. Many positions are correct within specific problem domains but are problematic in others. There are numerous situations in which 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 Affirmation: Intermixed control and recovery paths

10.1.2 Objection: Confusing exception handling with normal error handling

10.1.3 Objection: Difficulty retrofitting exception handling

10.1.4 Affirmation: Ambiguous values

10.1.5 Affirmation: Ambiguous data types

10.1.6 Affirmation: Enforcing error handling

10.1.7 Objection: Providing recovery handlers

10.1.8 Affirmation: Transforming failure types

10.1.9 Affirmation: Separation of concerns

10.1.10 Objection: 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