What is an exception What are the advantages of using exception handling in a program in C++?

  1. Introduction
  2. Arguments for using Exceptions
    1. Exceptions separate error-handling code from the normal program flow and thus make the code more readable, robust, and extensible.
    2. Throwing an exception is the only clean way to report an error from a constructor.
    3. Exceptions are hard to ignore, unlike error codes.
    4. Exceptions are easily propagated from deeply nested functions.
    5. Exceptions can be, and often are, user defined types that carry much more information than an error code.
    6. Exception objects are matched to the handlers by using the type system.
  3. Arguments against using Exceptions
    1. Exceptions break code structure by creating multiple invisible exit points that make code hard to read and inspect.
    2. Exceptions easily lead to resource leaks, especially in a language that has no built-in garbage collector and finally blocks.
    3. Learning to write Exception safe code is hard.
    4. Exceptions are expensive and break the promise to pay only for what we use.
    5. Exceptions are hard to introduce to legacy code.
    6. Exceptions are easily abused for performing tasks that belong to normal program flow.
  4. Conclusion

1. Introduction

Exceptions have been a part of C++ since early 1990s and are sanctioned by the standard to be the mechanism for writing fault-tolerant code in this language. However, many developers for various reasons choose not to use exceptions, and voices that are skeptical of this language feature are still numerous and loud: Raymond Chen's article Cleaner, more elegant, and wrong, Joel Spolsky's blog Exceptions, and Google C++ Style Guide are some of the frequently quoted texts that advise against the use of exceptions.

Rather than taking a side in this debate, I am trying to present a balanced view of pros and cons of using exceptions. The purpose of this article is not to convince readers to use exceptions or error codes, but help them make an informed decision that is best for their particular project. I have structured the article as a list of six arguments for using exceptions and six arguments against it that can often be heard in the C++ community.

2. Arguments for using Exceptions

2.1 Exceptions separate error-handling code from the normal program flow and thus make the code more readable, robust, and extensible.

To illustrate the point, we'll compare the usage of two simple socket libraries that differ only in the error handling mechanism. Here is how we could use them to fetch HTML from a web site:

string get_html[const char* url, int port] { Socket client[AF_INET, SOCK_STREAM, IPPROTO_TCP]; client.connect[url, port]; stringstream request_stream; request_stream

Chủ Đề