4-Exceptions & Memory Flashcards
Exception handling is used when
the system can recover from the error causing the exception
so permits to catch and handle errors
What happens if there’s no catch block for the exception
- Unwinding the stack, terminate() -> abord(): quits the program
If a function throws a const object, what should the catch handler argument type be?
It must be declared as a const
If a function is provided a list of exceptions to throw, what could possibly go wrong?
If an exception not in the list is thrown, the unexpected exception handler is invoked, which terminates the program (Not recommended).
Exceptions thrown in constructors (copy cons and destructor)
- In order to catch the exception, the exception handler must have access to a copy cons for the thrown object
- Exceptions thrown in cons cause destructors to be called for any objects built as part of the object.
The new operator behavior (single and array objects)
singles
- allocates enough memory to hold an object: if not, throws an exception
- then, it calls the cons to initialize the object in memory that was allocated
arrays
- new[] is called and allocates memory for all elements of the array
string *ps = new string[10]
- delete[]: if only delete is callled, it will only deconstruct the first object
What happends if String *title = new String(“kicks”) throws an exception
String *title = new String(“kicks”)
if string cons threw exception: if new succeded, then delete needs to be called on the allocated, but uninitialized storage.
if new threw exception: then no memory was allocated and operator delete should not be thrown