The purpose of this quiz is to give you a chance to focus your knowledge of simple exceptions in C++.
When calling code that might throw an exception, we should try to execute it and then catch any possible exception(s).
If you aren't sure what standard library functions you are calling are going to use exceptions, just look them up on a handy reference site like cppreference.com. (That's the one where the standards committee members hang out and share their knowledge and experience.)
TRUE ✓ | FALSE ✗ | exceptions are meant to handle extreme situations. | ||
---|---|---|---|---|
TRUE ✗ | FALSE ✓ | For instance, many string class methods use them to report invalid capitalization of data. | ||
TRUE ✓ | FALSE ✗ | An exception is also returned by new and new[] to report allocation failure. | ||
TRUE ✓ | FALSE ✗ | A caught exception won't trouble your program any longer — no more crashing. |
Another way to avoid an exception crashing your program — at least for dynamic memory purposes — is to use the nothrow overloads of the allocation operators.
If you don't, you'll have to watch for and catch the bad_alloc exception that these operators normally throw.
Try not to throw an exception in a frivolous situation where a return value of bool or enum type could have sufficed to indicate the problem encountered to callers.
When you do decide to, however, you can use a standard exception from the stdexcept header or you can derive one from the base class exception yourself. This class can be found in the library header exception. Alternatively, you can even use a regular type like long or string. But this is frowned upon heavily!
Show code to allocate dynamic memory without crashing the program by handling any exception(s) that may arise. Embed your code in a templated function to allocate any type of space. When the caller specifies a silly or invalid size for the array, make sure to allocate a single object instead.
template <typename AllocT> inline AllocT * allocate(AllocT & p, size_t len) { try { p = (len < 2) ? new AllocT : new AllocT[len]; } catch (bad_alloc) { p = nullptr; } return p; }