CPSC 427: Object-Oriented Programming

Similar documents
CPSC 427: Object-Oriented Programming

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

C++ Namespaces, Exceptions

Object-Oriented Principles and Practice / C++

Exceptions, Case Study-Exception handling in C++.

C++ Exception Handling 1

CPSC 427: Object-Oriented Programming

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

17.1 Handling Errors in a Program

2. How many runtime error messages associated with exception? a) 2 b) 4 c) 5 d) infinite

05-01 Discussion Notes

Laboratorio di Tecnologie dell'informazione

CPSC 427: Object-Oriented Programming

Exception with arguments

IS 0020 Program Design and Software Tools

Programming in C++: Assignment Week 8

G52CPP C++ Programming Lecture 16

Programming in C++: Assignment Week 8

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

Intermediate Programming, Spring 2017*

This examination has 11 pages. Check that you have a complete paper.

Homework 4. Any questions?

CS11 Introduction to C++ Fall Lecture 6

Exceptions. Why Exception Handling?

CS11 Advanced C++ Fall Lecture 3

C++_ MARKS 40 MIN

Object Oriented Programming

Assertions and Exceptions

Exception Handling in C++

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

CS102 C++ Exception Handling & Namespaces

! Errors can be dealt with at place error occurs

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

CSCI-1200 Data Structures Fall 2017 Lecture 26 C++ Exceptions

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

The format for declaring function templates with type parameters

04-24/26 Discussion Notes

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

TEMPLATES AND EXCEPTION HANDLING

ECE 462 Midterm Exam 2. 10:30-11:20AM, October 19, 2007

C++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

CSCI 104 Exceptions. Mark Redekopp David Kempe

Introduction. Common examples of exceptions

int main() { int account = 100; // Pretend we have $100 in our account int withdrawal;

CPSC 427: Object-Oriented Programming

C++ Exception Handling. Dr. Md. Humayun Kabir CSE Department, BUET

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

1 Introduction to C++ C++ basics, simple IO, and error handling

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

DATA STRUCTURES AND ALGORITHMS LECTURE 08 QUEUES IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD

Exception Handling Pearson Education, Inc. All rights reserved.

Interview Questions of C++

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CPSC 427: Object-Oriented Programming

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Exception Handling Alternatives (Part 2)

CSC 330. An Exception is. Handling Exceptions. Error Handling. Assertions. C++ Exception. Example

More Group HW. #ifndef Stackh #define Stackh. #include <cstdlib> using namespace std;

C++ Programming Fundamentals

Object-Oriented Programming (OOP) Fundamental Principles of OOP

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Absolute C++ Walter Savitch

void fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) {

ECE 462 Fall 2011, Third Exam

A Whirlwind Tour of C++

Exceptions in Java

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

COMP6771 Advanced C++ Programming

Stack memory - "scratch pad" memory that is used by automatic variables.

CPSC 427: Object-Oriented Programming

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

CPSC 427a: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

mywbut.com Exception Handling

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

CPSC 427: Object-Oriented Programming

Templates and Vectors

CSE 303: Concepts and Tools for Software Development

Exceptions and Design

Internationalization and Error Handling

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

Exception handling. Aishy Amer. Lecture Outline: Introduction Types or errors or exceptions Conventional error processing Exception handling in C++

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

7.1 Optional Parameters

CPSC 427: Object-Oriented Programming

G52CPP C++ Programming Lecture 17

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

AN OVERVIEW OF C++ 1

Chapter 5 Errors. Bjarne Stroustrup

Linked List using a Sentinel

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.

CS24 Week 3 Lecture 1

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

Transcription:

CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 19 November 7, 2018 CPSC 427, Lecture 19, November 7, 2018 1/18

Exceptions Thowing an Exception Catching an Exception CPSC 427, Lecture 19, November 7, 2018 2/18

Exceptions CPSC 427, Lecture 19, November 7, 2018 3/18

Exceptions An exception is an event that prevents normal continuation. Exceptions may be due to program errors or data errors, but they may also be due to external events: File not found. Insufficient permissions. Network failure. Read error. Out of memory error. How to respond to different kinds of exceptions is application-dependent. CPSC 427, Lecture 19, November 7, 2018 4/18

Exception handling When an exception occurs, a program has several options: Try again. Try something else. Give up. Problem: Exceptions are often detected at a low level of the code. Knowledge of how to respond resides at a higher level. CPSC 427, Lecture 19, November 7, 2018 5/18

C-style solution using status returns The C library functions generally report exceptions by returning status values or error codes. Advantages: How to handle exception is delegated to the caller. Disadvantages: Every caller must handle every possible exception. Exception-handling code becomes intermingled with the normal operation code, making program much more difficult to comprehend. CPSC 427, Lecture 19, November 7, 2018 6/18

C++ exception mechanism C++ exception mechanism is a means for a low-level routine to report an exception directly to a higher-level routine. This separates exception-handling code from normal processing code. An exception is reported using the keyword throw. An exception is handled in a catch block. Each routine in the chain between the reporter and the handler is exited cleanly, with all destructors called as expected. CPSC 427, Lecture 19, November 7, 2018 7/18

Thowing an Exception CPSC 427, Lecture 19, November 7, 2018 8/18

Throwing an exception (demo 19a-Exceptions) throw is followed by an exception value. Exceptions are usually objects of a user-defined exception type. Example: throw AgeError("Age can t be negative"); Exception class definition: class AgeError { string msg; public: AgeError(string s) : msg(s) {} ostream& printerror(ostream& out) const { return out<< msg; } }; CPSC 427, Lecture 19, November 7, 2018 9/18

Catching an Exception CPSC 427, Lecture 19, November 7, 2018 10/18

Catching an exception A try region defines a section of code to be monitored for exceptions. Immediately following are catch blocks for handling the exceptions. try {... //run some code } catch (AgeError& aerr) { // report error cout<< "Age error: "; aerr.printerror( cout )<< endl; //... recover or abort } The catch parameter should generally be a reference parameter as in this example. CPSC 427, Lecture 19, November 7, 2018 11/18

What kind of object should an exception throw? catch filters the kinds of exceptions it will catch according to the type of object thrown. For this reason, each kind of exception should throw it s own type of object. That way, an exception handler appropriate to that kind of exception can catch it and process it appropriately. While it may be tempting to throw a string that describes the error condition, it is difficult to process such an object except by printing it out and aborting (like Fatal()). Properly used, exceptions are much more powerful than that. CPSC 427, Lecture 19, November 7, 2018 12/18

Example: Stack template throws exception It is an error to pop an empty stack. We have given several sample stack implementations. Here s what they each do when attemption to pop an empty stack: Demo 08-Brackets 19-Virtual/linear.cpp 19b-Exceptions-stack Action on empty pop error undefined (programmer must avoid) return nullptr throw exception Demo 19b-Exceptions-stack gives one way to handle an empty pop error using throw. CPSC 427, Lecture 19, November 7, 2018 13/18

Polymorphic exception classes A catch clause can catch polymorphic exception objects. Demo 19c-Exceptions-cards w shows how this can be used to provide finer error control. The base exception class Bad has a virtual print function. Derived from it are two classes BadSuit and BadSpot. The catch clause catch (bad& bs) {...} will catch all three kinds of errors: bad suit, bad spot, and bad both. These are errors that can arise while reading a playing card from the user. CPSC 427, Lecture 19, November 7, 2018 14/18

Standard exception class The standard C++ library provides a polymorphic base class std::exception from which all exceptions thrown by components of the C++ Standard library are derived. These are: exception bad alloc bad cast bad exception bad typeid ios base::failure description thrown by new on allocation failure thrown by a failed dynamic cast thrown when an exception type doesn t match any catch thrown by typeid thrown by functions in the iostream library (from http://www.cplusplus.com/doc/tutorial/exceptions/) CPSC 427, Lecture 19, November 7, 2018 15/18

Catching standard exceptions Class std::exception contains a virtual function const char* what() const; that is overridden in each derived exception class to provide a meaningful error message. Because the base class is polymorphic, it is possible to write a single catch handler that will catch all derived exception objects. Example: catch (exception& e) { cerr << "exception caught: " << e.what() << endl; } CPSC 427, Lecture 19, November 7, 2018 16/18

Deriving your own exception classes from std::exception #include <iostream> #include <exception> using namespace std; class myexception: public exception { virtual const char* what() const throw() { return "My exception happened"; } } myex; // declares class and instantiates it int main () { try { throw myex; } catch (exception& e) { cout << e.what() << endl; } return 0; } CPSC 427, Lecture 19, November 7, 2018 17/18

Multiple catch blocks Can have multiple catch blocks to catch different classes of exceptions. They are tried in order, so the more specific should come before the more general. Can have a catch-all block catch (...) that catches all exceptions. (This should be placed last.) Demo 19c-Exceptions-cards has an example of this as well. CPSC 427, Lecture 19, November 7, 2018 18/18