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 your linked list problem
- The user trys to access current when it is nullptr.
- In either case, you as a good programmer probably caught the error
- But what do you do?
- You can crash the program (exit, _exit, abort, ...)
- You can try to fix it, but what if you are wrong?
- You can print an error message, but who will see that?
- You can return a value, but what if that is wrong?
- 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.