O'Reilly logo

Professional C++ by Scott J. Kleper, Nicholas A. Solter

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 15. Handling Errors

Inevitably, your C++ programs will encounter errors. The program might be unable to open a file, the network connection might go down, or the user might enter an incorrect value, to name a few possibilities. Professional C++ programs recognize these situations as exceptional, but not unexpected, and handle them appropriately. The C++ language provides a feature called exceptions to support error handling in your programs.

The code examples in this book so far have virtually ignored error conditions for brevity. This chapter rectifies that simplification by teaching you how to incorporate error handling into your programs from their beginnings. It focuses on C++ exceptions, including the details of their syntax, and describes how to employ them effectively to create well-designed error-handling programs. This chapter presents:

  • An overview of C++ error handling, including pros and cons of exceptions in C++

  • Syntax of exceptions

    • Throwing and catching exceptions

    • Uncaught exceptions

    • Throw lists

  • Exception class hierarchies and polymorphism

    • The C++ exception hierarchy

    • Writing your own exception classes

  • Stack unwinding and cleanup

  • Common error handling issues

    • Memory allocation errors

    • Errors in constructors and destructors

Errors and Exceptions

Even perfectly written programs encounter errors and exceptional situations. No program exists in isolation; they all depend on external facilities such as networks and file systems, on external code such as third-party libraries, and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required