Programming in C++ 1. Learning Outcome  At the end of this slide, student able to:  Understand what is Inheritance?  Compare between inheritance and.

Slides:



Advertisements
Similar presentations
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
HST 952 Computing for Biomedical Scientists Lecture 7.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Class Hierarchy (Inheritance)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 13 Exception.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
C++ for the MFE class at UC Berkeley Session #2 Yuli Kaplunovsky MFE, MBA, MS-Tax, CFA (408)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
Java Exception Handling
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
CS203 Java Object Oriented Programming Errors and Exception Handling.
COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 12 Exception Handling and Text.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
1 Chapter 18 Exception Handling. 2 Motivations F Program runs into a runtime error –program terminates abnormally F How can you handle the runtime error.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling Exceptions and language features to handle them.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Exception Handling.
Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
Exceptions "A slipping gear could let your M203 grenade launcher fire when you least expect it. That would make you quite unpopular in what's left of your.
Programming in C++ 1. Learning Outcome At the end of this slide, student able to:  Identify the different types of error in your program  Understand.
Lecture objectives  Differences between Java and C#  Understand and use abstract classes  Casting in Java: why is it important?  Master exceptions.
1.  At the end of this slide, student able to understand the concept of multithreading and exception handling. 2.
COMP Exception Handling Yi Hong June 10, 2015.
Peter Andreae Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 Implementing.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 15 Exceptions and Assertions Nothing is impossible.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Chapter 13 Exception Handling
Chapter 13 Exception Handling
Why exception handling in C++?
Chapter 12 Exception Handling and Text IO
Exceptions "A slipping gear could let your M203 grenade launcher fire when you least expect it. That would make you quite unpopular in what's left of your.
Chapter 12 Exception Handling
EXCEPTION HANDLING OR ERROR HANDLING.
Chapter 11 Exception Handling and Text I/O
Managing Errors and Exceptions
Chapter 13 Exception Handling
Chapter 12 Exception Handling and Text IO Part 1
Coming up Exceptions An Example The Throws keyword Try and Catch
Presentation transcript:

Programming in C++ 1

Learning Outcome  At the end of this slide, student able to:  Understand what is Inheritance?  Compare between inheritance and derivation  Distinguish between constructors and destructors  Understand the overriding function  Understand the virtual methods  Examine the implementation of the concept of polymorphism.  Examine the problems with single inheritance  Define multiple and virtual inheritance.  What are the limitations of abstract data types? 2

3 Overview Inheritance is a way to establish relationships between objects

Derivation  Derivation is the definition of a new class by extending one or more existing classes.  Create new class Dog that derive from Mammal. “class Dog : public Mammal” 4

 #include  using std::cout;  using std::endl;   enum BREED { GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };   class Mammal  {  public:  // constructors  Mammal():itsAge(2), itsWeight(5){}  ~Mammal(){}   //accessors  int GetAge() const { return itsAge; }  void SetAge(int age) { itsAge = age; }  int GetWeight() const { return itsWeight; }  void SetWeight(int weight) { itsWeight = weight; }   //Other methods  void Speak()const { cout << " Mammal sound!\n" ; }  void Sleep()const { cout << " shhh. I’m sleeping.\n" ; }   protected:  int itsAge;  int itsWeight;  };   class Dog : public Mammal  {  public:   // Constructors  Dog():itsBreed(GOLDEN){}  ~Dog(){}   // Accessors  BREED GetBreed() const { return itsBreed; }  void SetBreed(BREED breed) { itsBreed = breed; }  // Other methods  void WagTail() const { cout << " Tail wagging...\n" ; }  void BegForFood() const { cout << " Begging for food...\n" ; }   private:  BREED itsBreed;  };   int main()  {  Dog Fido;  Fido.Speak();  Fido.WagTail();  cout << "Fido is " << Fido.GetAge() << " years old" << endl;  return 0;  } 5

 #include  using namespace std;  class Base {  public:  char* name;  void display() {  cout << name << endl;  }  };  class Derived: public Base {  public:  char* name;  void display() {  cout << name << ", " << Base::name << endl;  }  };  int main() {  Derived d;  d.name = "Derived Class";  d.Base::name = "Base Class";  // call Derived::display()  d.display();  // call Base::display()  d.Base::display();  } 6

Constructor  A class constructor is a special member function of a class that is executed whenever we create new objects of that class. 7

 #include   using namespace std;   class Line  {  public:  void setLength( double len );  double getLength( void );  Line(); // This is the constructor   private:  double length;  };   // Member functions definitions including constructor  Line::Line(void)  {  cout << "Object is being created" << endl;  }   void Line::setLength( double len )  {  length = len;  }   double Line::getLength( void )  {  return length;  }  // Main function for the program  int main( )  {  Line line;   // set line length  line.setLength(6.0);  cout << "Length of line : " << line.getLength() <<endl;   return 0;  } 8

Destructor  A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class. 9

 #include   using namespace std;   class Line  {  public:  void setLength( double len );  double getLength( void );  Line(); // This is the constructor declaration  ~Line(); // This is the destructor: declaration   private:  double length;  };   // Member functions definitions including constructor  Line::Line(void)  {  cout << "Object is being created" << endl;  }  Line::~Line(void)  {  cout << "Object is being deleted" << endl;  }   void Line::setLength( double len )  {  length = len;  }   double Line::getLength( void )  {  return length;  }  // Main function for the program  int main( )  {  Line line;   // set line length  line.setLength(6.0);  cout << "Length of line : " << line.getLength() <<endl;  line.setLength(9.0);  cout << "Length of line : " << line.getLength() <<endl;  return 0;  } 10

Overriding function  Redefining a base class function in the derived class to have our own implementation is referred as overriding. 11

 #include using namespace std; class Base { public: virtual void myfunc() { cout << "Base::myfunc.." << endl; } }; class Derived : public Base { public: void myfunc() { cout << "Derived::myfunc.." << endl; } }; void main() { Derived d; d.myfunc(); } 12

Virtual Function  A virtual function is a special type of function that resolves to the most-derived version of the function with the same signature.  To make a function virtual, simply place the “virtual” keyword before the function declaration. 13

 #include  using namespace std;  class B  { public:  virtual void display() /* Virtual function */  { cout<<"Content of base class.\n"; } };  class D1 : public B  { public: void display()  { cout<<"Content of first derived class.\n"; } };  class D2 : public B { public: void display() {  cout<<"Content of second derived class.\n"; } };  int main() {  B *b;  D1 d1;  D2 d2; /* b->display();  // You cannot use this code here because the function of base class is virtual.  */ b = &d1;  b->display(); /* calls display() of class derived D1 */  b = &d2;  b->display(); /* calls display() of class derived D2 */  return 0; } 14

Polymorphism  C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.  That means, polymorphism can be described as CALLING TECHNIQUE 15

Multiple Inheritance/Virtual Inheritance 16

Example of Exception 17 ExceptionDescription ArithmeticExceptionArithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsExceptionArray index is out-of-bounds. ArrayStoreExceptionAssignment to an array element of an incompatible type. ClassCastExceptionInvalid cast. IllegalArgumentExceptionIllegal argument used to invoke a method. IllegalMonitorStateExceptionIllegal monitor operation, such as waiting on an unlocked thread. IllegalStateExceptionEnvironment or application is in incorrect state. IllegalThreadStateExceptionRequested operation not compatible with current thread state. IndexOutOfBoundsExceptionSome type of index is out-of-bounds. NegativeArraySizeExceptionArray created with a negative size. NullPointerExceptionInvalid use of a null reference. NumberFormatExceptionInvalid conversion of a string to a numeric format. SecurityExceptionAttempt to violate security. StringIndexOutOfBoundsAttempt to index outside the bounds of a string. UnsupportedOperationExceptionAn unsupported operation was encountered.

Other Exception  AWTException  AclNotFoundException  ActivationException  AlreadyBoundException  ApplicationException  ArithmeticException  ArrayIndexOutOfBoundsException  AssertionException  BackingStoreException  BadAttributeValueExpException  BadBinaryOpValueExpException  BadLocationException  BadStringOperationException  BatchUpdateException  BrokenBarrierException  CertificateException  ChangedCharSetException  CharConversionException  CharacterCodingException  ClassCastException  ClassNotFoundException  CloneNotSupportedException  ClosedChannelException  ConcurrentModificationException  DataFormatException 18 DatatypeConfigurationException DestroyFailedException EOFException Exception ExecutionException ExpandVetoException FileLockInterruptionException FileNotFoundException FishFaceException FontFormatException GSSException GeneralSecurityException IIOException IOException IllegalAccessException IllegalArgumentException IllegalClassFormatException IllegalStateException IndexOutOfBoundsException InputMismatchException InstantiationException InterruptedException InterruptedIOException IntrospectionException InvalidApplicationException InvalidMidiDataException InvalidPreferencesFormatException InvalidTargetObjectTypeException

 InvocationTargetException  JAXBException  JMException  KeySelectorException  LastOwnerException  LineUnavailableException  MalformedURLException  MarshalException  MidiUnavailableException  MimeTypeParseException  NamingException  NegativeArraySizeException  NoSuchElementException  NoSuchFieldException  NoSuchMethodException  NoninvertibleTransformException  NotBoundException  NotOwnerException  NullPointerException  NumberFormatException  ObjectStreamException  ParseException  ParserConfigurationException  PrintException  PrinterException  PrivilegedActionException  PropertyVetoException 19 ProtocolException RefreshFailedException RemarshalException RemoteException RuntimeException SAXException SOAPException SQLException SQLWarning SSLException ScriptException ServerNotActiveException SocketException SyncFailedException TimeoutException TooManyListenersException TransformException TransformerException URIReferenceException URISyntaxException UTFDataFormatException UnknownHostException UnknownServiceException UnmodifiableClassException UnsupportedAudioFileException UnsupportedCallbackException UnsupportedEncodingException UnsupportedFlavorException UnsupportedLookAndFeelException UnsupportedOperationException UserException XAException XMLParseException XMLSignatureException XMLStreamException XPathException ZipException

Friendly Advice about Exception  Actually, it is very difficult to remember all exception especially to junior programmer. However, the programmer can use online recourses. 20

21 System Errors System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

22 Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.

23 Runtime Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.

24 Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }

25 Catching Exceptions try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; }... catch (ExceptionN exVar3) { handler for exceptionN; }

26 Catching Exceptions

27 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements

28 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed

29 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Next statement in the method is executed

30 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Suppose an exception of type Exception1 is thrown in statement2

31 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The exception is handled.

32 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed.

33 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The next statement in the method is now executed.

34 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; statement2 throws an exception of type Exception2.

35 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Handling exception

36 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Execute the final block

37 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Rethrow the exception and control is transferred to the caller

Exercise  Develop a C++ program that can save 10 book information (string) & display 10 book information (string), and also the program will give WARNING if user try to key in integer (this part you should use exception handling).  InputMismatchException 38