Introduction to Exceptions
- Chapter 14, READ IT!
- Your code can encounter errors
- Consider a rational number class.
- The user somehow manages to set a 0 denonominator
- Or our queue class
- The user trys to Front or Dequeue on an empty queue.
- In either case, you as a good programmer probably caught the error
- You always check to see that the queue has an element before you call Dequeue.
- But what do you do as a queue implementor if they do not?
- You can crash the program (exit, _exit, abort, ...)
- You can try to fix it, but what if you are wrong?
- How could you fix this situation?
- You can print an error message, but who will see that?
- You can return a value, but what if that is wrong?
- What value should you return?
- If the user did not check to see if there was a value in the queue, will they check to see if the return value is valid?
- What is an invalid value anyway?
- Exceptions are built to handle these exceptional but not unexpected situations.
- The vector
at
function does this error checking
- Catching exceptions
- Exceptions are caught in a try-catch block
- reference
- We will build this up slowly.
-
try
- This marks the beginning of a code block that could contain an error.
- It is followed by one or more catch blocks.
-
catch (...)
- This is the most basic catch block
- It matches all exceptions.
- It contains code to "clean up" after the exception.
- More later.
- see case1,cpp.
-
throw
- The second half of the equation is the throw expression
-
throw expression
- Constructs the expression object.
- Unwinds back through the stack until it reaches an appropriate exception handler
- invokes all destructors for objects that go out of lifetime
- If the exception is called anywhere but in a constructor, the corresponding destructor is called.
- If the exception is called in a method everything is fine.
- If no corresponding catch is found, the program is aborted.
- We will be back to this in the future.
- But look at throw.cpp.