500 likes | 811 Views
Exceptions, Templates and STL. 2. Exceptions. Indicate that something unexpected has occurred or been detectedAllow program to deal with the problem in a controlled mannerCan be as simple or complex as program design requiresThe line containing the throw statement is the throw pointControl is passed to another part of the program known as the exception handlerWhen an exception is thrown by a function, the function aborts.
E N D
1. Exceptions, Templates, and the Standard Template Library (STL)
2. Exceptions, Templates and STL 2 Exceptions Indicate that something unexpected has occurred or been detected
Allow program to deal with the problem in a controlled manner
Can be as simple or complex as program design requires
The line containing the throw statement is the throw point
Control is passed to another part of the program known as the exception handler
When an exception is thrown by a function, the function aborts
3. Exceptions, Templates and STL 3 Coding for Exceptions int main()
{
int numerator[3]={10,0,10};
int denominator[3]= {2,10,0};
double answer;
for (int i=0; i<3;i++)
{
answer = divide(numerator[i], denominator[i]);
cout<<numerator[i]<<" divided by "<<denominator[i]<<" = "<<answer<<endl;
}
cout<<endl<<endl;
for (int i=0; i<3;i++)
{
answer = divide_throw(numerator[i], denominator[i]);
cout<<numerator[i]<<" divided by "<<denominator[i]<<" = "<<answer<<endl;
}
return 0;
}
4. Exceptions, Templates and STL 4 Coding for Exceptions double divide(int n, int d)
{
if (d==0)
{
cout<<"ERROR: Cannot divide by zero ";
return 0;
}
else
return static_cast<double>(n)/d;
}
double divide_throw(int n, int d)
{
if (d==0)
{
throw "ERROR: Cannot divide by zero\n";
}
else
return static_cast<double>(n)/d;
}
5. Exceptions, Templates and STL 5 Coding for Exceptions - Output Output from function divide
10 divided by 2 = 5
0 divided by 10 = 0
ERROR: Cannot divide by zero 10 divided by 0 = 0
Output from function divide_throw
10 divided by 2 = 5
0 divided by 10 = 0
This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
6. Exceptions, Templates and STL 6 Exceptions - Terminology Exception: object or value that signals an error
Throw an exception: send a signal that an error has occurred
throw – followed by an argument, is used to throw an exception
Catch/Handle an exception: process the exception; interpret the signal
try – followed by a block { }, is used to invoke code that throws an exception
catch – followed by a block { }, is used to detect and process exceptions thrown in preceding try block. Takes a parameter that matches the type thrown.
7. Exceptions, Templates and STL 7 Exceptions – Flow of Control A function that throws an exception is called from within a try block
If the function throws an exception, the function terminates and the try block is immediately exited.
A catch block to process the exception is searched for in the source code immediately following the try block.
If a catch block is found that matches the exception thrown, it is executed.
If no catch block that matches the exception is found, the program terminates.
8. Exceptions, Templates and STL 8
9. Exceptions, Templates and STL 9
10. Exceptions, Templates and STL 10
11. Exceptions, Templates and STL 11
12. Exceptions, Templates and STL 12 Catch Exception and Reprompt int main()
{
int num1, num2; // To hold two numbers
double quotient; // To hold the quotient of the numbers
bool goodResult; //test if no exception thrown
do{
cout << "Enter two numbers: ";
cin >> num1 >> num2;
goodResult=true;
try
{ quotient = divide(num1, num2);
cout << "The quotient is " << quotient << endl;
}
catch (char *exceptionString)
{ goodResult=false;
cout <<exceptionString;
}
} while (!goodResult);
cout << "End of the program.\n";
return 0;
}
13. Exceptions, Templates and STL 13 Exceptions - Notes An integer can be thrown to signal a predefined error code
try
{ quotient = divide(num1, num2);
cout << "The quotient is " << quotient << endl;
}
catch (int exceptionInt)
{ goodResult=false;
cout <<“Error code”<<exceptionInt;
}
In the function write:
if (denominator == 0) throw 333;
and then look up the code in a library or table
14. Exceptions, Templates and STL 14 Exceptions - Notes Predefined functions such as new may throw exceptions
The value that is thrown does not need to be used in catch block.
in this case, no name is needed in catch parameter definition
catch block parameter definition does need the type of exception being caught
15. Exceptions, Templates and STL 15 Exception Not Caught? An exception will not be caught if
it is thrown from outside of a try block or,
there is no catch block that matches the data type of the thrown exception
If an exception is not caught, the program will terminate
16. Exceptions, Templates and STL 16 Exceptions and Objects An exception class can be defined in a class and thrown as an exception by a member function
An exception class may have:
no members: used only to signal an error
members: pass error data to catch block
A class can have more than one exception class
17. Exceptions, Templates and STL 17
18. Exceptions, Templates and STL 18
19. Exceptions, Templates and STL 19
20. Exceptions, Templates and STL 20
21. Exceptions, Templates and STL 21 Handling Multiple Exceptions To differentiate between a negative width and length, two classes can be created and each called based on the type of error
In Rectangle.h include:
public:
class NegativeWidth { }; // Exception class for a negative width
class NegativeLength { }; // Exception class for a negative length
and in main change the try blocks to the following:
try
{
myRectangle.setWidth(width);
myRectangle.setLength(length);
cout << "The area of the rectangle is “ << myRectangle.getArea() << endl;
}
catch (Rectangle::NegativeWidth)
{ cout<<"Error: A negative value was given "<< "for the rectangle's width.\n";
}
catch (Rectangle::NegativeLength)
{ cout<<"Error:A negative value was given "<< "for the rectangle's length.\n";
}
22. Exceptions, Templates and STL 22 Recovering From Exceptions Within the catch block, prompt the user to re-enter the correct length or width
23. Exceptions, Templates and STL 23 Recovering From Exceptions
24. Exceptions, Templates and STL 24 Extracting Data from the Exception Class Sometimes, we want an exception object to pass data back to the exception handler
We want the Rectangle class not only to signal when a negative value was entered, but to pass back that value as well
This can be accomplished by expanding the exception class with members in which data can be stored. For example:
25. Exceptions, Templates and STL 25 What Happens After catch Block? Once an exception is thrown, the program cannot return to throw point. The function executing throw terminates (does not return), other calling functions in try block terminate, resulting in unwinding the stack
If an exception is thrown by the member function of a class object, then the class destructor is called
If objects were created in the try block and an exception is thrown, they are destroyed.
26. Exceptions, Templates and STL 26 Nested try Blocks try/catch blocks can occur within an enclosing try block
Exceptions caught at an inner level can be passed up to a catch block at an outer level:
catch ( )
{
...
throw; // pass exception up
} // to next level
27. Exceptions, Templates and STL 27 Nested try Blocks #include <iostream>
using namespace std;
void doA();
void doB();
int main()
{
char *exception1;
try{
doA();
}
catch(char *exception1) {
cout<<"Exception 1 handled in main"<<endl;
}
return 0;
}
28. Exceptions, Templates and STL 28 Handling the bad_alloc Exception When the new operator is unable to allocate the requested amount of memory, a bad_alloc exception is thrown. It can be handled as follows:
#include <iostream>
#include <new> // Needed for bad_alloc
using namespace std;
int main()
{ double *ptr; // Pointer to double
try
{ ptr = new double [1000000000]; }
catch (bad_alloc)
{ cout << "Insufficient memory.\n"; }
return 0;
}
29. Exceptions, Templates and STL 29 Function Templates Function template: a generic function that can work with any data type.
It is a template and by itself does not cause memory to be used
An actual instance of the function is created in memory when the compiler encounters a call to the template function
The programmer writes the specifications of the function, but substitutes parameters for data types
When called, compiler generates code for specific data types in function call
30. Exceptions, Templates and STL 30 Function Template Example template <class T>
T square(T num)
{
return num * num;
}
31. Exceptions, Templates and STL 31 Function Template Example template <class T>
T square(T num)
{
return num * num;
}
Call a template function in the usual manner:
int ival = 3;
double dval = 12.5;
cout << sqaure(ival); // displays 9
cout << sqaure(dval); // displays 156.25
32. Exceptions, Templates and STL 32 Function Template Swap Example #include <iostream>
using namespace std;
template <class T>
void swapVars(T &var1, T &var2)
{
T temp;
temp = var1;
var1 = var2;
var2 = temp;
}
33. Exceptions, Templates and STL 33 Function Template Swap Example int main()
{ char firstChar, secondChar; // Two chars
int firstInt, secondInt; // Two ints
double firstDouble, secondDouble; // Two doubles
// Get and swapVars two chars
cout << "Enter two characters: ";
cin >> firstChar >> secondChar;
swapVars(firstChar, secondChar);
cout << firstChar << " " << secondChar << endl;
// Get and swapVars two ints
cout << "Enter two integers: ";
cin >> firstInt >> secondInt;
swapVars(firstInt, secondInt);
cout << firstInt << " " << secondInt << endl;
// Get and swapVars two doubles
cout << "Enter two floating-point numbers: ";
cin >> firstDouble >> secondDouble;
swapVars(firstDouble, secondDouble);
cout << firstDouble << " " << secondDouble << endl;
return 0;
}
34. Exceptions, Templates and STL 34 Function Template Notes Can define a template to use multiple data types:
template<class T1, class T2>
Example:
template<class T1, class T2>
// T1 and T2 will be replaced in the called function
//with the data types of the arguments
double mpg(T1 miles, T2 gallons) {return miles / gallons}
35. Exceptions, Templates and STL 35 Function Template Notes #include <iostream>
using namespace std;
template <class T1, class T2>
int largest(const T1 &var1, T2 &var2)
{
if (sizeof(var1) > sizeof(var2))
return sizeof(var1);
else
return sizeof(var2);
}
int main()
{ int i = 0;
char c = ' ';
float f = 0.0;
double d = 0.0;
cout << "Comparing an int and a double, the largest\n"
<< "of the two is " << largest(i, d) << " bytes.\n";
cout << "Comparing an char and a float, the largest\n"
<< "of the two is " << largest(c, f) << " bytes.\n";
return 0;
}
36. Exceptions, Templates and STL 36 Function Template Notes Function templates can be overloaded Each template must have a unique parameter list
template <class T>
T sum(T val1, T val2)
{return val1 + val2}
template <class T>
T sum(T val1, T val2, Tval3)
{return val1 + val2 + val3}
37. Exceptions, Templates and STL 37 Defining Your Own Templates Templates are often appropriate for multiple functions that perform the same task with different parameter data types
Develop function using usual data types first, then convert to a template:
add template prefix template <class T>
convert data type names in the function to a type parameter (i.e., a T type) in the template
38. Exceptions, Templates and STL 38 Class Templates Classes can also be represented by templates. When a class object is created, type information is supplied to define the type of data members of the class.
Unlike functions, classes are instantiated by supplying the type name (int, double, string, etc.) at object definition
39. Exceptions, Templates and STL 39 Class Template Example template <class T>
class grade
{
private:
T score;
public:
grade(T);
void setGrade(T);
T getGrade()
};
40. Exceptions, Templates and STL 40 Class Template Example Pass type information to class template when defining objects:
grade<int> testList[20];
grade<double> quizList[20];
Use as ordinary objects once defined
41. Exceptions, Templates and STL 41 #include <iostream>
using namespace std;
template <class T>
class Grade
{
private:
T score;
public:
Grade(T);
void setGrade(T);
T getGrade();
};
template <class T>
Grade<T>::Grade(T s)
{ score = s; }
template <class T>
void Grade<T>:: setGrade(T s)
{ score = s; }
template <class T>
T Grade<T>:: getGrade()
{ return score; }
42. Exceptions, Templates and STL 42 Class Templates and Inheritance Class templates can inherit from other class templates:
template <class T>
class Rectangle
{ ... };
template <class T>
class Square : public Rectangle<T>
{ ... };
Must use type parameter T everywhere base class name is used in derived class
43. Exceptions, Templates and STL 43 Introduction to the Standard Template Library Standard Template Library (STL): a library containing templates for frequently used data structures and algorithms
Not supported by many older compilers
44. Exceptions, Templates and STL 44 Standard Template Library Two important types of data structures in the STL:
containers: classes that stores data and imposes some organization on it
iterators: like pointers; mechanisms for accessing elements in a container
45. Exceptions, Templates and STL 45 Containers Two types of container classes in STL:
sequence containers: organize and access data sequentially, as in an array. These include vector, deque, and list
vector – efficiently inserts values to its end, insertions at other points is not as efficient
deque – efficiently inserts values to its front and end, not as efficient at inserting at other points
list – efficiently inserts values anywhere; doesn’t provide random access
associative containers: use keys to allow data elements to be quickly accessed. These include set, multiset, map, and multimap
46. Exceptions, Templates and STL 46 Containers associative containers: use keys to allow data elements to be quickly accessed. These include set, multiset, map, and multimap
set – stores a set of keys, no duplicates
multiset – stores a set of keys, duplicates allowed
map – map a set of keys to data elements; only one key per data, no duplicates
multimap - map a set of keys to data elements; many keys per data element are allowed, duplicates are allowed
47. Exceptions, Templates and STL 47 Iterators Generalization of pointers, used to access information in containers
Four types:
forward (uses ++)
bidirectional (uses ++ and -- )
random-access
input (can be used with cin and istream objects)
output (can be used with cout and ostream objects)
vectors and deques require random access iterators; lists, sets, multisets, maps and multimaps require bidirectional iterators
48. Exceptions, Templates and STL 48 Algorithms STL contains algorithms implemented as function templates to perform operations on containers.
Requires algorithm header file
algorithm includes
49. Exceptions, Templates and STL 49 STL Example // A simple demonstration of STL algorithms
#include <iostream>
#include <vector> // Required for the vector type
#include <algorithm> // Required for STL algorithms
using namespace std;
int main()
{
int count; // Loop counter
// Define a vector object.
vector<int> vect;
// Use push_back to push values into the vector.
for (count = 0; count < 10; count++)
vect.push_back(count);
// Display the vector's elements.
cout << "The vector has " << vect.size()
<< " elements. Here they are:\n";
for (count = 0; count < vect.size(); count++)
cout << vect[count] << " ";
cout << endl;
50. Exceptions, Templates and STL 50 STL Example
51. Exceptions, Templates and STL 51 STL Example - Output