L7: Exceptions Problem Description Error Handling –terminate the program –return a value representing an error –return a legal value and leave the program.

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
C/c++ 4 Yeting Ge.
Lecture 9. 2 Exception  An exception is a unusual, often unpredictable event, detectable by software or hardware, that requires special processing occurring.
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.
1 Chapter 17-2 Templates and Exceptions Dale/Weems.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Review Linked list: Doubly linked list, insertback, insertbefore Remove Search.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Week 11 Exceptions.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
Exceptions and Exception Handling Carl Alphonce CSE116.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 7: Errors 1 Based on slides created by Bjarne Stroustrup.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
CS Advanced C++ Exception Handling Topic #5.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
. Plab – Tirgul 10 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Plab – Tirgul 8 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
Object Oriented Programming
CIS 270—Application Development II Chapter 13—Exception Handling.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
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.
Exceptions Handling Exceptionally Sticky Problems.
VB.Net - Exceptions Copyright © Martin Schray
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions and Program Correctness based on the original work by Dr. Roger deBry Version 1.1.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
LECTURE LECTURE 14 Exception Handling Textbook p
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
Exceptions Lecture 11 COMP 401, Fall /25/2014.
CSC241 Object-Oriented Programming (OOP) Lecture No. 22.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
Revisiting building. Preprocessing + Compiling 2 Creates an object file for each code file (.c ->.o) Each.o file contains code of the functions and structs.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Java Exceptions a quick review….
Recitation 7 – 3/18/02 Outline fork and scheduling Signals
Exception Handling in C++
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
CS212: Object Oriented Analysis and Design
Exceptions.
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Why exception handling in C++?
Chapter 17 Templates and Exceptions Part 2
Exceptions 10-May-19.
CMSC 202 Exceptions.
Presentation transcript:

L7: Exceptions Problem Description Error Handling –terminate the program –return a value representing an error –return a legal value and leave the program in an illegal state –call an error-handling routine –use exceptions Use inheritance to implement exceptions Resource Management Typeid Chapter 8 and 14 of Stroustrup

Exceptions See Chapter 8 and 14 of Stroustrup Library or class can detect run-time errors, but may not know what to do with them. Caller may know what to do with run-time error, but doesn't know how to detect them. What can be done?

Error Handling Possibilities include: –terminate the program –return a value representing an error –return a legal value and leave the program in an illegal state –call an error-handling routine –use exceptions

Terminate Program Default behaviour for uncaught exceptions in C++ Not appropriate for libraries

Error Value Return Often no plausible error value Inconvenient because error must be checked for every function call

Illegal State Behaviour of C library functions Global variable errno is set by library. Calling routine must explicitly check errno.

#include int main() { //if error, fopen returns NULL and sets errno FILE * f = fopen("filename", "r"); if (!f) // an error has occurred, check errno { // file doesn't exist if (errno==ENOENT) printf("No file\n"); // perror checks errno and prints message perror("An error occurred opening file"); exit(-1); }

Error Handling Routine Exceptions not meant to handle this case But error handling routine has to choose a mechanism for dealing with errors

#include void sighandler(int sig) { printf("received signal %d\n", sig); exit(-1); } int main() { // register the handler with a seg fault signal(SIGSEGV, sighandler); // do something to cause a seg fault delete (int*)-10; }

Exceptions Designed to support handling of errors and other exceptional conditions Non-local control structure based on stack unwinding An alternative to the usual return mechanism Some legitimate uses that are not related to errors

Stack Unwinding When an exception is thrown and control passes from a try block onto a handler, the C++ run time calls the destructors of all the automatic objects constructed since the beginning of the try block. This process is called stack unwinding.

Exceptions Exceptional does not necessarily mean –almost never happens, or –a disastrous event. Can be thought of as: –some part of the system couldn't do what it was asked to do So, don't use exceptions when errors can be handled locally.

Throw struct RangeError { int i; RangeError(int ii){i=ii;}; }; char to_char(int i) { if (i ::min() || i > numeric_limits ::max()) throw RangeError(i); return (char)i; }

Catch void g(int i) { try { char c = to_char(i); //... } catch (RangeError r) { cerr << can't convert << r.i << to char\n; }

Inheritance and Exceptions class Matherr {}; class Overflow : public Matherr {}; class Underflow: public Matherr {}; class Zerodivide: public Matherr {}; void f() { try { //... } catch (Overflow) {// handle overflow}; catch (Matherr) {// handle any other Matherr}; catch (...) {// handle any other exception}; }

Resource Management void use_file(const char *fn) { File *f = fopen(fn, r); try { // use f } catch (...) { fclose(f); throw; } fclose(f); }

Resource Allocation is Initialisation class FilePtr { private: FILE *p; public: FilePtr(const char *name, const char *a){ p = fopen(name, a);}; ~FilePtr(){if (p) fclose(p);}; };

Resource Allocation is Initialisation void use_file(const char *p) { FilePtr f(p, r); try { // use f } catch (...) { // handle exception }

typeid Given an object (or a variable), typeid operator retrieves the type of an object (or a variable) to which a pointer or a reference points. Can be used to discover things about the actual type (usually its name). An alternative to dynamic_cast.

Inheritance class Shape { public: virtual void draw() = 0; }; class Rectangle: public Shape { public: void draw() { cout << "draw a rectangle\n";}; }; class Circle : public Shape { public: void draw() { cout << "draw a circle\n"; }; };

Example 1: An Alternative to Downcasting void rotate(const Shape &shape) { if (typeid(shape)==typeid(Circle)) { cout << "rotate Circle\n"; } else if (typeid(shape)==typeid(Rectangle)) { cout << "rotate rectangle\n"; } Circle c; Rectangle r; rotate(c); // rotate Circle rotate(r); // rotate Rectangle

In the case of a polymorphic class (containing pure virtual functions), the typeid operator retrieves the most derived type of this object, if the argument of the typeid is an object (pointed by a pointer). If the argument is a pointer itself, the typeid operator regards the type of this object as the pointer of this class. Example 2

void f(Shape &circle, Shape *rectangle) { if(typeid(circle) == typeid(Circle)) cout << "a is of type Circle\n"; if(typeid(*rectangle) == typeid(Rectangle)) cout << "a is of type Rectangle\n"; Shape *s; if(typeid(rectangle) == typeid(s)) cout << "a is of type Shape\n"; } int main() { Circle c; Rectangle r; f( c, &r ); } Example 2

Example 3 In the case of a non-polymorphic class, the typeid operator retrieves the type of the object given. class C { public: C() {}; }; class D : public C { public: D() {}; };

Example 3 D d; C *c1 = &d; C &c2 = d; cout << "c1: " << typeid(*c1).name() << endl; // C cout << "c2: " << typeid(c2).name() << endl; // C