An exception looks somewhat like an alternate return mechanism and somewhat like a switchstatement, so you might be tempted to use an exception instead of these ordinary language mechanisms. This is a bad idea, partly because the exception-handling system is significantly less efficient than normal program execution; exceptions are a rare event, so the normal program shouldn’t pay for them. Also, exceptions from anything other than error conditions are quite confusing to the user of your class or function .
You’re not forced to use exceptions
Some programs are quite simple (small utilities, for example). You might only need to take input and perform some processing. In these programs, you might attempt to allocate memory and fail, try to open a file and fail, and so on. It is acceptable in these programs to display a message and exit the program, allowing the system to clean up the mess, rather than to work hard to catch all exceptions and recover all the resources yourself. Basically, if you don’t need to use exceptions, you don’t have to use them .
Another situation that arises is the modification of an existing program that doesn’t use exceptions. You might introduce a library that does use exceptions and wonder if you need to modify all your code throughout the program. Assuming you have an acceptable error-handling scheme already in place, the most straightforward thing to do is surround the largest block that uses the new library (this might be all the code in main( )) with a tryblock, followed by a catch(...)and basic error message). You can refine this to whatever degree necessary by adding more specific handlers, but, in any case, the code you’re forced to add can be minimal. It’s even better, of course, to isolate your exception-generating code in a tryblock and write handlers to convert the exceptions into your existing error-handling scheme .
It’s truly important to think about exceptions when you’re creating a library for someone else to use, especially in situations in which you can’t know how they need to respond to critical error conditions (recall the earlier discussions on exception safety and why there are no exception specifications in the Standard C++ Library) .
Typical uses of exceptions
Do use exceptions to do the following:
· Fix the problem and call the function which caused the exception again.
· Patch things up and continue without retrying the function.
· Do whatever you can in the current context and rethrow the same exception to a higher context.
· Do whatever you can in the current context and throw a different exception to a higher context.
· Terminate the program.
· Wrap functions (especially C library functions) that use ordinary error schemes so they produce exceptions instead.
· Simplify. If your exception scheme makes things more complicated, it is painful and annoying to use.
· Make your library and program safer. This is a short-term investment (for debugging) and a long-term investment (for application robustness) .
When to use exception specifications
The exception specification is like a function prototype: it tells the user to write exception-handling code and what exceptions to handle. It tells the compiler the exceptions that might come out of this function so that it can detect violations at runtime .
Of course, you can’t always look at the code and anticipate which exceptions will arise from a particular function. Sometimes, the functions it calls produce an unexpected exception, and sometimes an old function that didn’t throw an exception is replaced with a new one that does, and you get a call to unexpected( ). Any time you use exception specifications or call functions that do, consider creating your own unexpected( )function that logs a message and then either throws an exception or aborts the program .
As we explained earlier, you should avoid using exception specifications in template classes, since you can’t anticipate what types of exceptions the template parameter classes might throw .
Start with standard exceptions
Check out the Standard C++ library exceptions before creating your own. If a standard exception does what you need, chances are it’s a lot easier for your user to understand and handle .
If the exception type you want isn’t part of the standard library, try to derive one from an existing standard exception. It’s nice if your users can always write their code to expect the what( )function defined in the exception( )class interface .
If you create exceptions for your particular class, it’s a good idea to nest the exception classes either inside your class or inside a namespace containing your class, to provide a clear message to the reader that this exception is used only for your class. In addition, it prevents the pollution of the global namespace .
You can nest your exceptions even if you’re deriving them from C++ standard exceptions .
Use exception hierarchies
Using exception hierarchies is a valuable way to classify the types of critical errors that might be encountered with your class or library. This gives helpful information to users, assists them in organizing their code, and gives them the option of ignoring all the specific types of exceptions and just catching the base-class type. Also, any exceptions added later by inheriting from the same base class will not force all existing code to be rewritten—the base-class handler will catch the new exception .
Of course, the Standard C++ exceptions are a good example of an exception hierarchy and one on which you can build .
Multiple inheritance (MI)
As you’ll read in Chapter 9, the only essential place for MI is if you need to upcast an object pointer to two different base classes—that is, if you need polymorphic behavior with both of those base classes. It turns out that exception hierarchies are useful places for multiple inheritance because a base-class handler from any of the roots of the multiply inherited exception class can handle the exception .
Catch by reference, not by value
We explained in the section "Exception matching" earlier that you should catch exceptions by reference for two reasons:
· To avoid making a needless copy of the exception object when it is passed to the handler,
· To avoid object slicing when catching a derived exception as a base class object
Although you can also throw and catch pointers, by doing so you introduce more coupling—the thrower and the catcher must agree on how the exception object is allocated and cleaned up. This is a problem because the exception itself might have occurred from heap exhaustion. If you throw exception objects, the exception-handling system takes care of all storage .
Throw exceptions in constructors
Because a constructor has no return value, you’ve previously had two ways to report an error during construction: .
· Set a nonlocal flag and hope the user checks it.
· Return an incompletely created object and hope the user checks it.
This problem is serious because C programmers have come to rely on an implied guarantee that object creation is always successful, which is not unreasonable in C in which types are so primitive. But continuing execution after construction fails in a C++ program is a guaranteed disaster, so constructors are one of the most important places to throw exceptions—now you have a safe, effective way to handle constructor errors. However, you must also pay attention to pointers inside objects and the way cleanup occurs when an exception is thrown inside a constructor .
Читать дальше