Exceptions
Notes
- Exceptions are a mechanism for handling errors in a language.
- Some languages like python they are "use all of the time" mechanisms
- In C++ they are reserved for "something bad has happened"
- The c++ philosophy is that exceptions are for exceptional but not unexpected conditions.
- A good example is an array out of bounds error
- We know that these will occur
- We don't know what to do when they happen
- Please see error.cpp.
- In this case, the program has an array out of bounds index error
- The
atfunction sees this - And it throws an exception.
- Why exceptions?
- In your array class, what did you do when there was an index out of bounds error?
- You have several choices
- Ignore it
- this is bad and will lead to bad code
- And will probably lead to errors and uncontrolled crashes later.
- Print an error message
- this is so-so, but doesn't solve the problem
- And will probably lead to errors and uncontrolled crashes later.
- And the final user will not understand what the problem was from your error message.
- Ignore it
- Throwing an exception allows the programmer "higher up" in the code to deal with the problem.
- This is a radical solution however and bugs should be fixed, not dealt with by exceptions.
- Dealing with exceptions
- The c++ syntax is
-
try { code block } catch ( type id) { code block } catch (type id) { code block } catch (...) { code block }
- The
catch (type id) {}is called a handler - Semantics:
- Code within the try block is executed
- If an exception is thrown the run time system attempts to match the closets type in the catch block(s).
- If a match is found, the code in the catch block is executed.
- If no match is found and ... is a catch case, the code in this block is executed
- If no match is found and no ... is present, the program is terminated.
-
catch (...)must be the last handler listed. - Let's start simply.
- This is the simplest use.
- Look at error1.cpp.
- We will look at
throwlater, but take a look at error2a.cpp. - When an exception is thrown the call stack is unwound until
- A corresponding handler is found
- The program exits.
- Take a look at error2.cpp.
- Exceptions can be anything, but
- There is an exception hierarchy
- documentation.
-
- Use this with
#include <exception> - The base class (exception) contains
- A constructor
- Destructor
- Overloaded assignment operator
-
virtual const char* what() const noexcept - noexcept says that the function will not throw an exception!
- We saw that the string class threw 'std::out_of_range'
- So we can catch this specifically
- See error4.cpp.
- It is a good practice to catch exceptions as a constant reference.
- stoi converts from a string to an integer.
- It throws an exception if no conversion was possible.
- With the exception class
- The compiler is unhappy if you catch them out of order.
- ios_base::failure is a system_error is a runtime_error is an exception
- They should be caught in the opposite order
- see error4.cpp.