Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions & Templates

Similar presentations


Presentation on theme: "Exceptions & Templates"— Presentation transcript:

1 Exceptions & Templates http://www.cplusplus.com/doc/tutorial/exceptions/ http://www.cplusplus.com/reference/stl/

2 Error handling in C #define NO_SEATS_AVIALABLE -1 #define CREDITCARD _DECLINED -2 #define INCORRECT_FLIGHT_NUM -3 #define DATABASE_CONNECTIVITY_ISSUE -10 int book_tickets(customer_information, itinerary_info,... ) {.... return DATABASE_CONNECTIVITY_ISSUE;... return INCORRECT_FLIGHT_NUM;... return NO_SEATS_AVIALABLE;... return CREDITCARD _DECLINED;... return record_number; }

3 How that function is used? char *error_messages[] = { "No error", "No Seats Available", "Credit card declined",... "Database Connectivity Issue" } … if ((ret_code = book_tickets(...)) < 0) // ugly, but works! Another mechanism is switch() statement fprintf(stderr, error_messages[-ret_code]); else rec_num = ret_code; // proceed with normal processing.

4 try.. catch in C++ try { // code here throw xxx; } catch (int param) { cout << "int exception“ << param; } catch (char param) { cout << "char exception“ < param; } catch (...) { cout << "default exception"; }

5 Exceptions Almost anything can be thrown and caught. – char, int, string, double, or object m1 m2 m3 m4 e3 e2 e1

6 Exceptions: Examples Chapter 16

7 Return code vs. Exceptions Unlike Exception, type for “return code” should match with method’s return type. Exception logically goes directly to the code where it is handled, but what happens actually?

8 Macros (C) – remember? #define max(x, y) (x > y ? x : y) Equivalent method(s)? Following is just one of them. int max(int x, int y) { if (x > y) return x; else return y; }

9 Function Templates Template T max(T x, T y) { if (x > y) return x; else return y; } Examples: pr16-07.cpp, pr16-08.cpp, pr16-09.cpp

10 Standard Template Library Contains both Template Classes and Function Templates Reference: http://www.cplusplus.com/reference/stl/ http://www.cplusplus.com/reference/stl/

11 Template classes in STL Sequential Containers Vector – array list Deque – double ended queue List – linked list We will cover the following in future classes: Container adaptors Associative containers

12 Vector

13 STL algorithms (function templates) binary_search count for_each find max_elemet min_element random_shuffle Sort Example: pr16-14.cpp Reference: http://www.cplusplus.com/reference/algorithm/http://www.cplusplus.com/reference/algorithm/

14 deque container

15 list container You can still access the items like an array!

16 User defined template classes Example: pr16-11.cpp, pr16-12.cpp

17 STL algorthms Provided as part of C++ Standard Template Library. Example: pr16-14.cpp to pr16-19.cpp

18 Project 4 Class definition: Two extreme approaches – Pointers vs Indices


Download ppt "Exceptions & Templates"

Similar presentations


Ads by Google