680 likes | 691 Views
This guide explores error handling in OOP, covering introduction, types of exceptions, coding practices, and more. Learn how to handle errors effectively in your programs to prevent unexpected failures.
E N D
Object Oriented Programming Prepared by, Dr.R.Vasanthi Professor/CSE, Tagore Institute of Engineering and Technology, Deviyakurichi, Attur
Exception Handling • Topics: • Introduction • Errors and Error handling • Exceptions • Types of Exceptions • Coding Exceptions • Summary
Introduction • Users have high expectations for the code we produce. • Users will use our programs in unexpected ways. • Due to design errors or coding errors, our programs may fail in unexpected ways during execution
Introduction • It is our responsibility to produce quality code that does not fail unexpectedly. • Consequently, we must design error handling into our programs.
Errors and Error Handling • An Error is any unexpected result obtained from a program during execution. • Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program termination. • Errors should be handled by the programmer, to prevent them from reaching the user.
Errors and Error Handling • Some typical causes of errors: • Memory errors (i.e. memory incorrectly allocated, memory leaks, “null pointer”) • File system errors (i.e. disk is full, disk has been removed) • Network errors (i.e. network is down, URL does not exist) • Calculation errors (i.e. divide by 0)
Errors and Error Handling • More typical causes of errors: • Array errors (i.e. accessing element –1) • Conversion errors (i.e. convert ‘q’ to a number) • Can you think of some others?
Errors and Error Handling • Traditional Error Handling • 1. Every method returns a value (flag) indicating either success, failure, or some error condition. The calling method checks the return flag and takes appropriate action. • Downside: programmer must remember to always check the return value and take appropriate action. This requires much code (methods are harder to read) and something may get overlooked.
Errors and Error Handling • Traditional Error Handling • Where used: traditional programming languages (i.e. C) use this method for almost all library functions (i.e. fopen() returns a valid file or else null)
Errors and Error Handling • Traditional Error Handling • 2. Create a global error handling routine, and use some form of “jump” instruction to call this routine when an error occurs. • Downside: “jump” instruction (GoTo) are considered “bad programming practice” and are discouraged. Once you jump to the error routine, you cannot return to the point of origin and so must (probably) exit the program.
Errors and Error Handling • Traditional Error Handling • Where used: many older programming texts (C, FORTRAN) recommended this method to programmers. Those who use this method will frequently adapt it to new languages (C++, Java).
Errors and Error Handling • Exceptions – a better error handling • Exceptions are a mechanism that provides the best of both worlds. • Exceptions act similar to method return flags in that any method may raise and exception should it encounter an error. • Exceptions act like global error methods in that the exception mechanism is built into Java; exceptions are handled at many levels in a program, locally and/or globally.
Exceptions • What are they? • An exception is a representation of an error condition or a situation that is not the expected result of a method. • Exceptions are built into the Java language and are available to all program code. • Exceptions isolate the code that deals with the error condition from regular program logic.
Exceptions • How are they used? • Exceptions fall into two categories: • Checked Exceptions • Unchecked Exceptions • Checked exceptions are inherited from the core Java class Exception. They represent exceptions that are frequently considered “non fatal” to program execution • Checked exceptions must be handled in your code, or passed to parent classes for handling.
Exceptions • How are they used? • Unchecked exceptions represent error conditions that are considered “fatal” to program execution. • You do not have to do anything with an unchecked exception. Your program will terminate with an appropriate error message.
Exceptions • Examples: • Checked exceptions include errors such as “array index out of bounds”, “file not found” and “number format conversion”. • Unchecked exceptions include errors such as “null pointer”.
Exceptions • How do you handle exceptions? • Exception handling is accomplished through the “try – catch” mechanism, or by a “throws” clause in the method declaration. • For any code that throws a checked exception, you can decide to handle the exception yourself, or pass the exception “up the chain” (to a parent class).
Exceptions • How do you handle exceptions? • To handle the exception, you write a “try-catch” block. To pass the exception “up the chain”, you declare a throws clause in your method or class declaration. • If the method contains code that may cause a checked exception, you MUST handle the exception OR pass the exception to the parent class (remember, every class has Object as the ultimate parent)
Coding Exceptions • Try-Catch Mechanism • Wherever your code may trigger an exception, the normal code logic is placed inside a block of code starting with the “try” keyword: • After the try block, the code to handle the exception should it arise is placed in a block of code starting with the “catch” keyword.
Coding Exceptions • Try-Catch Mechanism • You may also write an optional “finally” block. This block contains code that is ALWAYS executed, either after the “try” block code, or after the “catch” block code. • Finally blocks can be used for operations that must happen no matter what (i.e. cleanup operations such as closing a file)
Coding Exceptions • Example • try {… normal program code}catch(Exception e) {… exception handling code}
Coding Exceptions • Passing the exception • In any method that might throw an exception, you may declare the method as “throws” that exception, and thus avoid handling the exception yourself • Example • public void myMethod throws IOException {… normal code with some I/O}
Coding Exceptions • Types of Exceptions • All checked exceptions have class “Exception” as the parent class. • You can use the actual exception class or the parent class when referring to an exception • Where do you find the exception classes? • Reference books such as “Java in a Nutshell” (O’Reilly, 2001), or the Java Documentation.
Coding Exceptions • Types of Exceptions • Examples: • public void myMethod throws Exception { • public void myMethod throws IOException { • try { … }catch (Exception e) { … } • try { … }catch (IOException ioe) { … }
Code Examples • 1. Demonstration of an unchecked exception (NullPointerException) • 2. Demonstration of checked exceptions: • Passing a DivideByZeroException • Handling a DivideByZeroException
Summary • Exceptions are a powerful error handling mechanism. • Exceptions in Java are built into the language. • Exceptions can be handled by the programmer (try-catch), or handled by the Java environment (throws).
Contents • 1. Key OOP Features • 2. Inheritance Concepts • 3. Inheritance Examples • 4. Implementing Inheritance in C++ • 5. Polymorphism • 6. Inclusion (Dynamic Binding) • 7. Virtual Function Examples • 8. C++ Pros and Cons
1. Key OOP Features • ADTs (done in the last section) • Inheritance • Polymorphism
2. Inheritance Concepts • Derive a new class (subclass) from an existing class (base class or superclass). • Inheritance creates a hierarchy of related classes (types) which share code and interface.
CommunityMember Employee Student Faculty Staff Administrator Teacher University community members
Circle Sphere Square Cube Triangle Tetrahedron Shape class hierarchy Shape TwoDimensionalShape ThreeDimensionalShape
logo card owner’s name inheritsfrom (isa) mastercard visacard americanexpress hologram category pin Credit cards
4. Implementing Inheritance in C++ • Develop a base class called student • Use it to define a derived class called grad_student
The Student Class Hierarchy student print()year_group() student_id,year, name inherits (isa) grad_student dept,thesis print()
Student Class class student {public: student(char* nm, int id, int y); void print(); int year_group() { return year; }private: int student_id; int year; char name[30];};
Member functions student::student(char* nm, int id, int y){ student_id = id; year = y; strcpy(name, nm);}void student::print(){ cout << "\n" << name << ", " << student_id << ", " << year << endl;}
Graduate Student Class class grad_student: public student {public: grad_student(char* nm, int id, int y, char* d, char* th); void print();private: char dept[10]; char thesis[80];};
Member functions grad_student::grad_student(char* nm, int id, int y, char* d, char* th) :student(nm, id, y){ strcpy(dept, d); strcpy(thesis, th);}void grad_student::print(){ student::print(); cout << dept << ", " << thesis << endl;}
Use int main(){ student s1("Jane Doe", 100, 1); grad_student gs1("John Smith", 200, 4, "Pharmacy", "Retail Thesis"); cout << "Student classes example:\n"; cout << "\n Student s1:"; s1.print(); cout << “Year “ << s1.year_group() << endl; : continued
cout << "\n Grad student gs1:"; gs1.print(); cout << “Year “ << gs1.year_group() << endl; :
Using Pointers student *ps; grad_student *pgs; ps = &s1; cout << "\n ps, pointing to s1:"; ps->print(); ps = &gs1; cout << "\n ps, pointing to gs1:"; ps->print(); pgs = &gs1; cout << "\n pgs, pointing to gs1:"; pgs->print(); return 0;}
Output $ g++ -Wall -o gstudent gstudent.cc$ gstudentStudent classes example: Student s1:Jane Doe, 100, 1Year 1 Grad student gs1:John Smith, 200, 4Pharmacy, Retail ThesisYear 4 : continued
student print() used. ps, pointing to s1:Jane Doe, 100, 1 ps, pointing to gs1:John Smith, 200, 4 pgs, pointing to gs1:John Smith, 200, 4Pharmacy, Retail Thesis$ grad_student print() used.
Notes • The choice of print() depends on the pointer type, not the object pointed to. • This is a compile time decision (called static binding).
5. Polymorphism Webster: "Capable of assuming various forms." Four main kinds: 1. coercion a / b 2. overloading a + b continued
3. inclusion (dynamic binding) • Dynamic binding of a function call to a function. 4. parametric • The type argument is left unspecified and is later instantiated e.g generics, templates
6. Inclusion (dynamic binding) 5.1. Dynamic Binding in OOP 5.2. Virtual Function Example 5.3. Representing Shapes 5.4. Dynamic Binding Reviewed