Exceptions Exceptions are unexpected events that occur during the execution of a program. An exception can be the result of an error condition or simply an unanticipated input. Exceptions can be thought of as being object themselves. Error Exception Handling try throw (exception) catch (error type).. //handle the error Example:(problem) int a,b cin >> a cin >> b // b = 0 cout << a/b // divided by Zero int *ptr = new int[10000] // null ptr *ptr = 4 // memory error solution : int a, b ; cin >> a ; cin >> b ; try if ( b!= 0) cout << a / b else throw (b) Asst. Lec. Zainab Mahmood Fadhil Page 1
int *ptr = new int [10000] if ( ptr == Null ) throw ( out of memory ) *ptr = 4 catch (int i ) cout << i ; return 0 ; catch ( char * s) cout << s ;return 0 general catch catch( exception-type identifier) cout << an error occurred return 0 // exceptions with arguments #include <iostream> #include <string> using namespace std; /////////////////////////////////////////////////// class Distance //English Distance class private: int feet; float inches; public: //------------------------------------------------- class InchesEx //exception class public: Asst. Lec. Zainab Mahmood Fadhil Page 2
string origin; //for name of routine float ivalue; //for faulty inches value InchesEx(string or, float in) //2-arg constructor origin = or; //store string ivalue = in; //store inches ; //end of exception class //------------------------------------------------- Distance() //constructor (no args) feet = 0; inches = 0.0; //------------------------------------------------- Distance(int ft, float in) //constructor (two args) if(in >= 12.0) throw InchesEx( 2-arg constructor, in); feet = ft; inches = in; //------------------------------------------------- void getdist() //get length from user cout << \nenter feet: ; cin >> feet; cout << Enter inches: ; cin >> inches; if(inches >= 12.0) throw InchesEx( getdist() function, inches); //------------------------------------------------- void showdist() //display distance Asst. Lec. Zainab Mahmood Fadhil Page 3
cout << feet << \ - << inches << \ ; ; /////////////////////////////////////////////////// int main() try //Templates and Exceptions Distance dist1(17, 3.5); //2-arg constructor Distance dist2; //no-arg constructor dist2.getdist(); //get value //display distances cout << \ndist1 = ; dist1.showdist(); cout << \ndist2 = ; dist2.showdist(); catch(distance::inchesex ix) //exception handler cout << \ninitialization error in << ix.origin <<.\n Inches value of << ix.ivalue << is too large. ; cout << endl; return 0; Asst. Lec. Zainab Mahmood Fadhil Page 4
typedef defines a synonym for the specified type-declaration typedef type-declaration synonym for class,struct,union and enum declarations, typedef declaration do not introduce new types, they introduce new names for existing types. example 1) typedef unsigned long ulong ulong x // same as unsigned long x 2) typedef struct mytag mystruct ; mystruct ms ; // same as struct mytag ms 3) struct node typedef node *link struct node int elem link next // link is ptr to struct node 4) typedef struct. point ; point pt // instead of strut point-tag pt assert evaluates an expression and when the result is false,abort the program void assert (int expression) Asst. Lec. Zainab Mahmood Fadhil Page 5
examples assert (str!= NULL) // can not be NULL assert(*str!= \0 ) // ptr can not be empty assert (strlen(str)) > 2 // length must exceed 2 enum an enumeration consists of a set of named integer constants, by default the first enumerator has a value of 0. examples enum bool false, true // means false = 0, true = 1 enum colors R,G,B // means R= 0, G = 1, B = 2 Data types to class Conversion classname object (datatype) or object = classname ( datatype) or object = datatype example String :: String (char *a) len = strlen ( a) p = new char [len+1] strcpy (p, a ) string s1,s2 char * ptr = test Asst. Lec. Zainab Mahmood Fadhil Page 6
s1= string (ptr) s2=ptr // char * class string s3 (ptr ) class time int h, m public : time (int t) h= t / 60 m = t % 60 int i = 85 time t1( i ) time t2 t2 = i Asst. Lec. Zainab Mahmood Fadhil Page 7
Data structure: is a data object together with the relationships (functions) that exist among the instances and among the individual elements that compose an instance. Abstraction is ``the idea of a quality thought of apart from any particular object or real thing having that quality''. For example, we can think about the size of an object without knowing what that object is. Similarly, we can think about the way a car is driven without knowing its model or make. Abstraction is used to suppress irrelevant details while at the same time emphasizing relevant ones. The benefit of abstraction is that it makes it easier for the programmer to think about the problem to be solved. Abstract data type (ADT ): set of all possible values (the domain) of an encapsulated data object plus the specifications of the operations that are provided to create and manipulate the data. ADT provide a specification of the instances and operation. Data representation 1.vector list (formula-based) 2. linked list (chain) Linear lists Linear list is a data object of the form (e1,e2,,en) where n islength of elements. when n=0, the list is empty, Linear list have several operations (method) like create( ),destroy( ), length( ), IsEmpty ( ), find( ), Asst. Lec. Zainab Mahmood Fadhil Page 8
elements : [0] [1] [2] [3] maxsize-1 1 2 3 4. Length= 4 Element position(i) = i - 1 we have discussed, an array is an ordered set, which consist of a fixed number of elements. No deletion or insertion operations are performed on arrays. Another main disadvantage is its fixed length; we cannot add elements to the array. Lists overcome all the above limitations. A list is an ordered set consisting of a varying number of elements to which insertion and deletion can be made. A list represented by displaying the relationship between the adjacent elements is said to be a linear list. // class specification Template < class T > class linearlist int length int maxsize T * element Public : linearlist(int maxlistsize = 10 ) ~ LinearList( ) delete [ ] element bool Isempty( ) return ( length == 0 ) bool find ( int, T&) Asst. Lec. Zainab Mahmood Fadhil Page 9
int search ( T&) LinearList<T> Delete ( int,t &) ~ LinearList<T> Inseart ( int,t &) void output (LinearList<T>) ; // class implementation #include<iostream> using namespace std; template <class T> class LinearList int length; int maxsize; T *element; public: LinearList(int maxlistsize=10); ~LinearList() delete [ ]element; int Length() return length; bool Isempty() return (length==0); bool Find(int, T&); int Search(T); LinearList<T>& Delete(int, T&); void Insert(int, T); void output( ); ; Asst. Lec. Zainab Mahmood Fadhil Page 10
template<class T> LinearList<T> :: LinearList(int max) maxsize = max; element = new T[maxsize]; length = 0; template<class T> bool LinearList<T> ::Find(int k, T& x) if(k<1 k>length()) return false; x = element[k-1]; return true; template<class T> int LinearList<T> ::Search(T x) for (int i=0; i<length(); i++) if(element[i]==x) return ++i; return 0; template<class T> LinearList<T>& LinearList<T> ::Delete(int k, T& x) if(find(k,x)) for(int i=k; i<length(); i++) element[i-1] = element[i]; length--; Asst. Lec. Zainab Mahmood Fadhil Page 11
else return *this; throw("out of bounds"); template<class T> void LinearList<T> ::Insert(int k, T x) if(k<0 k>length()) throw("out of bounds"); if(length() == maxsize) throw("list is full"); for(int i=length()-1; i>=k; i--) element[i+1] = element[i]; element[k]= x; length++; template<class T> void LinearList<T> ::output() for(int i=0; i<length(); i++) cout<<element[i]<<" "; void main( ) try LinearList<int> L(5); cout<<"length = " << L.Length() <<endl; cout<<"isempty = " << L.Isempty() << endl; Asst. Lec. Zainab Mahmood Fadhil Page 12
L.Insert(0,2); L.Insert(1,6); L.Insert(2,7); L.Insert(3,9); L.Insert(4,2); L.output( ); L.Insert(5,100); cout<<"list is "; L.output(); cout<<endl; cout<<"is Empty= "<<L.Isempty( ) <<endl; int z; L.Find(1,z); cout<<"first element is " << z << endl; cout<<"length = " << L.Length() <<endl; cout<<"search location of element 7: "<<L.Search(7)<<endl; L.Delete(4,z); cout<<"deleted element is " << z << endl; cout<< "List is "; L.output( ); cout<<endl<<"length = " << L.Length() <<endl; cout<<endl; catch(char *s) cout<<s; Asst. Lec. Zainab Mahmood Fadhil Page 13