Exception Handling
Exception Handling
Introduction
try
{
Some_Statements
<some code with a throws statement or a function
invocation that might throw an exception>
Some_More_Statements
}
catch(int e)
{
cout << e << " donuts, and no milk!\n";
<< " Go buy some milk.\n";
}
Looks like function definition with
int parameter!
Not a function, but works similarly
Throw like "function call"
catch-block Parameter
Recall: catch(int e)
"e" called catch-block parameter
Each catch block can have at most ONE
catch-block parameter
Does two things:
1. type name specifies what kind of thrown
value the catch-block can catch
2. Provides name for thrown value caught;
can "do things" with value
Multiple Throws and Catches
std::bad_alloc
2
This can be thrown by new.
std::bad_cast
3
This can be thrown by dynamic_cast.
std::bad_exception
4 This is useful device to handle unexpected exceptions in a C++
program.
std::bad_typeid
5
This can be thrown by typeid.
std::logic_error
6
An exception that theoretically can be detected by reading the code.
C++ Standard Exceptions
std::domain_error
7 This is an exception thrown when a mathematically invalid domain is
used.
std::invalid_argument
8
This is thrown due to invalid arguments.
std::length_error
9
This is thrown when a too big std::string is created.
std::out_of_range
10 This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().
std::runtime_error
11 An exception that theoretically cannot be detected by reading the
code.
std::overflow_error
12
This is thrown if a mathematical overflow occurs.
Standard Library exception
classes