OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.

Slides:



Advertisements
Similar presentations
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
Advertisements

Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 1 Exceptions exceptiona program.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exceptions and Exception Handling Carl Alphonce CSE116.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
CS Advanced C++ Exception Handling Topic #5.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
OOP Etgar 2008 – Recitation 91 Object Oriented Programming Egar 2008 Recitation 9.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
OOP Etgar 2008 – Recitation 51 Object Oriented Programming Etgar 2008 Recitation 5.
Exceptions David Rabinowitz. March 3rd, 2004 Object Oriented Design Course 2 The Role of Exceptions Definition: a method succeeds if it terminates in.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Object Oriented Programming
Handling ErrorstMyn1 Handling Errors Up to this point we haven't worried much about errors or exceptions. First, let's distinguish between errors and exceptions.
1 CSC241: Object Oriented Programming Lecture No 27.
BASE CLASSES AND INHERITANCE CHAPTER 4. Engineer Class.
Slides Credit Umair Javed LUMS Web Application Development.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Object Oriented Programming Elhanan Borenstein Lecture #4.
Exceptions Handling Exceptionally Sticky Problems.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 16: Exceptions,
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
Overview of C++ Templates
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
LECTURE LECTURE 14 Exception Handling Textbook p
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Chapter 2 Objects and Classes
Motivation for Generic Programming in C++
Exception handling.
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Why exception handling in C++?
Exception Handling.
Standard Version of Starting Out with C++, 4th Edition
Exceptions, Templates, and the Standard Template Library (STL)
CMSC 202 Exceptions.
Presentation transcript:

OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8

OOP Spring 2007 – Recitation 82 Templates Generic Programming

OOP Spring 2007 – Recitation 83 Why? Often we meet algorithms, data structures or classes that are independent of the concrete type used in them. QuickSort can sort anything (if it can be compared). List can store anything. But how can we write generic algorithms and data structures?

OOP Spring 2007 – Recitation 84 Bad Solutions Using void* pointers: –Type-unsafe. –Error-prone. –Very unfriendly. Deriving all classes from one superclass: –Type-unsafe. –Demands specific interface from all classes. Both solutions disallow homogenous containers.

OOP Spring 2007 – Recitation 85 Templates A template allows passing a type as a parameter to a class or a function. This means that we can write classes and functions that are independent of the types they work with. Actually, a template is a recipe for creating families of classes and functions.

OOP Spring 2007 – Recitation 86 Swap() Consider the function swap() – the code is identical if it swaps two int s, two Rational s or two string s. void swap(int& a, int& b) { int temp = a; a = b; b = temp; }

OOP Spring 2007 – Recitation 87 Function Templates We can say that to the compiler by defining a function template: template void swap(T& a, T& b) { T temp = a; a = b; b = temp; } Within the template, T is another type, just like int or double.

OOP Spring 2007 – Recitation 88 Template Instantiation The compiler will use this template to instantiate swap() for types it needs: –When it needs to swap int s, it will generate a version for int s. –If it needs to swap string s, it will generate a new version for string s. The versions it generates will have no connection to one another (apart from similar name).

OOP Spring 2007 – Recitation 89 Lack of Conversions The compiler decides which version to instantiate based on the parameters types. –This is called template argument deduction. Conversions are not considered for this. –I.e., these calls will not compile: int i; short s; double d; swap(i, d);// no version for int and a double swap(i, s);// no version for int and a short The only conversions used are –conversion to const pointer or reference, –array and function to pointer.

OOP Spring 2007 – Recitation 810 Class Templates What about classes? Obviously, the code for ListOComplex will work for Rational s, int s or string s, if we didn’t hardwire the type into it. We can define a class template for a List, and List users will specify the concrete type when creating List objects. –The compiler will create instantiated classes as needed.

OOP Spring 2007 – Recitation 811 Class List template class List { public: List(const List&); bool push_front(const T&); T pop_front(); … }; Within List ’s methods, T is another type, just like int or double.

OOP Spring 2007 – Recitation 812 Instantiated Classes With class templates we need to specify the type parameter to create an object: List listOcomplex; List listOint; The compiler creates an instance of class List for Complex es and an instance for int s. They have nothing to do with one another. Note that copy c’tor in List has a parameter of type List, not List. –Both forms can be used – but the former only within the template itself.

OOP Spring 2007 – Recitation 813 Exceptions Error-handling mechanism

OOP Spring 2007 – Recitation 814 Why? Consider what happens when an error occurs in a program that consists of separate modules. Often the action that needs to be taken depends on the calling module rather than on the module that found the error. –A string doesn’t know what to do if it cannot allocate memory. The user of the string does. And what if the caller of the caller knows how to fix the error?

OOP Spring 2007 – Recitation 815 Exceptions Exceptions are program anomalies that occur during runtime (out-of-memory, pop- on-empty-stack, division-by-zero, etc.). Exception handling is a mechanism that allows two separately developed modules to communicate when exception occurs.

OOP Spring 2007 – Recitation 816 Throwing and Catching A module that detects an error has occurred signals it by throwing an exception of appropriate type. The module in the calling chain that knows how to handle the exception declares that by catching an exception of that type. –A pop() in Stack can throw popOnEmpty, and Stack ’s user can catch it and know that pop() didn’t succeed because it’s empty.

OOP Spring 2007 – Recitation 817 Why Exceptions? Exceptions: –Separate exceptional logic from normal logic. –Supported by the compiler. –Can carry any amount of information from thrower to the catcher. –Can be used in constructors. But impose runtime overhead. Returning error codes is still used.

OOP Spring 2007 – Recitation 818 throw An exception is an object of some type. The program part that has detected an error that it cannot handle, throws an exception (which is an object) of some type. This is done using the throw expression.

OOP Spring 2007 – Recitation 819 Example class popOnEmpty {};// Exceptions are objects, class pushOnFull {};// need to define the classes int Stack::pop() {// Stack from recitation 1 if (_top_index == 0) throw popOnEmpty();// Used to be "return 0" return _contents[--_top_index]; } void Stack::push(int el) { if (_top_index == _size) throw pushOnFull();// Used to be "return false" _contents[_top_index++] = el; return true; }

OOP Spring 2007 – Recitation 820 Example Notes Notice that now push() doesn’t return a value, and pop() returns only elements of the stack. Since throw throws an object, the corresponding class needs to be defined beforehand. It’s best to use separate classes for exceptions.

OOP Spring 2007 – Recitation 821 throw Creates an Object throw creates a temporary object of the given type and “passes it on”. –Note the () in throw pushOnFull(); ‏ This creates a pushOnFull object using the default constructor. –Had class pushOnFull had a constructor with int parameter (for example), we could write: throw pushOnFull(el); –The handler would then know what element wasn’t pushed.

OOP Spring 2007 – Recitation 822 Catching To be handled, an exception needs to be caught. This is done using try - catch construct. Operations that can throw exception are enclosed in a try block, and following that block a series of catch clauses, each defining how to handle specific type of exception.

OOP Spring 2007 – Recitation 823 Example int main() { Stack s(10); try { s.push(1); // More pops, pushes, printouts, etc. } catch (popOnEmpty) { cout << "Caught popOnEmpty\n"; } catch (pushOnFull) { cout << "Caught pushOnFull\n"; } cout << "Done\n"; return 0; }

OOP Spring 2007 – Recitation 824 catch Clauses Each catch clause defines how to handle a specific type of exception that might have occurred in the preceding try block. The clauses are examined top down until a matching catch is found. If none is found, the exception propagates to the caller. If a matching catch clause is found, its body is executed and execution resumes after the last catch (for that try block).

OOP Spring 2007 – Recitation 825 Exception Propagation Notice that a try - catch block only needs to handle exceptions it knows how to “fix”. Anything is doesn’t handle propagates to the caller of that function. When exception tries to propagate out of main(), the STL terminate() function is called, which by default calls abort().

OOP Spring 2007 – Recitation 826 Exception Declaration The () part in catch is called exception declaration. It can be either type declaration or an object declaration. …catch (popOnEmpty) {// Type declaration cout << "Caught popOnEmpty\n"; } catch (pushOnFull e) {// Object declaration cout << e.val() << " cannot be pushed\n"; } In object declaration the exception object that was thrown is given a name and can be accessed. This allows the exception object to carry additional information about the error.

OOP Spring 2007 – Recitation 827 Catching Everything If someone ( main(), for example) wants to handle any exception that can be thrown, it can use catch(...) : try { //… } catch (...) { cout << "Unknown exception occurred\n"; } Obviously, it should come last in the list of catch es.

OOP Spring 2007 – Recitation 828 Catching by Reference Exception declaration is much like function parameter list. In particular, we can catch exception objects by reference: …catch (pushOnFull& e) {…} Otherwise the exception object is passed by-value into the catch clause. Using “catch-by-reference”: –Prevents unnecessary copying; –Allows changing the exception object; –Permits polymorphism.