Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions, Templates, and the Standard Template Library (STL)

Similar presentations


Presentation on theme: "Exceptions, Templates, and the Standard Template Library (STL)"— Presentation transcript:

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 (n)/d; } double divide_throw(int n, int d) { if (d==0) { throw "ERROR: Cannot divide by zero\n"; } else return static_cast (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 1)A function that throws an exception is called from within a try block 2)If the function throws an exception, the function terminates and the try block is immediately exited. 1)A catch block to process the exception is searched for in the source code immediately following the try block. 2)If a catch block is found that matches the exception thrown, it is executed. 3)If no catch block that matches the exception is found, the program terminates.

8 Exceptions, Templates and STL 8 From Program 16-1

9 Exceptions, Templates and STL 9 From Program 16-1 THIS WORKS in Code::Blocks char* msg; msg = "ERROR: Cannot divide by zero.\n"; if (denominator == 0) throw msg;

10 Exceptions, Templates and STL 10 What Happens in the Try/Catch Construct

11 Exceptions, Templates and STL 11 What if no exception is thrown?

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 Exception class definition

18 Exceptions, Templates and STL 18

19 Exceptions, Templates and STL 19

20 Exceptions, Templates and STL 20 Program 16-2 Output

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 // Get the rectangle's width. cout << "Enter the rectangle's width: "; cin >> width; // Store the width in the myRectangle object. while (tryAgain) { try { myRectangle.setWidth(width); // If no exception was thrown, then the // next statement will execute. tryAgain = false; } catch (Rectangle::NegativeWidth) { cout << "Please enter a non-negative width: "; cin >> width; } // Get the rectangle's length. cout << "Enter the rectangle's length: "; cin >> length; // Store the length in the myRectangle object. tryAgain = true; while (tryAgain) { try { myRectangle.setLength(length); // If no exception was thrown, then the // next statement will execute. tryAgain = false; } catch (Rectangle::NegativeLength) { cout << "Please enter a non-negative length: "; cin >> length; }

23 Exceptions, Templates and STL 23 Recovering From Exceptions Enter the rectangle's width: -4 Please enter a non-negative width: -6 Please enter a non-negative width: 6 Enter the rectangle's length: -9 Please enter a non-negative length: 9 The rectangle's area is 54

24 Exceptions, Templates and STL 24 Extracting Data from the Exception Class 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: class NegativeWidth { private: int value; public: NegativeWidth(int val) { value = val; } int getValue() const { return value; } }; Which is thrown by throw NegativeWidth(w); And caught by: catch (Rectangle::NegativeWidth e) { cout<< "Error: "<<e.getValue()<< " is an invalid value for the" <<" rectangle's width.\n"; }

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 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; } void doA(){ char *exception1; try{ doB(); } catch(char *exception1) { cout<<"Exception 1 in doA(),rethrown“ <<endl; throw; } void doB(){ char *exception1; try{ throw exception1; } catch(char *exception1) { cout<<"Exception 1 in doB(),rethrown“ <<endl; throw; } Exception 1 in doB(),rethrown Exception 1 in doA(),rethrown Exception 1 in main, handled in main

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 #include // 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 T square(T num) { return num * num; } template prefix generic data type type parameter What gets generated when square is called with an int: What gets generated when square is called with a double: int square(int num) { return num * num; } double square(double num) { return num * num; }

31 Exceptions, Templates and STL 31 Function Template Example template 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 using namespace std; template 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 Example: template // 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 using namespace std; template 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; } Comparing an int and double, the largest of the two is 8 bytes Comparing a char and a float, the largest of the two is 4 bytes

36 Exceptions, Templates and STL 36 Function Template Notes Function templates can be overloaded Each template must have a unique parameter list template T sum(T val1, T val2) {return val1 + val2} template 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  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 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 testList[20]; grade quizList[20]; Use as ordinary objects once defined

41 Exceptions, Templates and STL 41 #include using namespace std; template class Grade { private: T score; public: Grade(T); void setGrade(T); T getGrade(); }; template Grade ::Grade(T s) { score = s; } template void Grade :: setGrade(T s) { score = s; } template T Grade :: getGrade() { return score; } int main() { Grade testlist[20]; testlist[0].setGrade(98); testlist[1].setGrade(85); testlist[2].setGrade(93); for (int i=0; i<3; i++) cout<<testlist[i].getGrade()<<" "; return 0; }

42 Exceptions, Templates and STL 42 Class Templates and Inheritance Class templates can inherit from other class templates: template class Rectangle {... }; template class Square : public Rectangle {... }; 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 binary_searchcount for_eachfind find_ifmax_element min_elementrandom_shuffle sort and others

49 Exceptions, Templates and STL 49 STL Example // A simple demonstration of STL algorithms #include #include // Required for the vector type #include // Required for STL algorithms using namespace std; int main() { int count; // Loop counter // Define a vector object. vector 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 // Randomly shuffle the vector's contents. random_shuffle(vect.begin(), vect.end()); // Display the vector's elements. cout << "The elements have been shuffled:\n"; for (count = 0; count < vect.size(); count++) cout << vect[count] << " "; cout << endl; // Now sort the vector's elements. sort(vect.begin(), vect.end()); // Display the vector's elements again. cout << "The elements have been sorted:\n"; for (count = 0; count < vect.size(); count++) cout << vect[count] << " "; cout << endl; // Now search for an element with the value 7. if (binary_search(vect.begin(), vect.end(), 7)) cout << "The value 7 was found in the vector.\n"; else cout << "The value 7 was not found in the vector.\n"; return 0; }

51 Exceptions, Templates and STL 51 STL Example - Output The vector has 10 elements. Here they are: 0 1 2 3 4 5 6 7 8 9 The elements have been shuffled: 8 1 9 2 0 5 7 3 4 6 The elements have been sorted: 0 1 2 3 4 5 6 7 8 9 The value 7 was found in the vector.


Download ppt "Exceptions, Templates, and the Standard Template Library (STL)"

Similar presentations


Ads by Google