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.

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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
COMP 121 Week 5: Exceptions and Exception Handling.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
CSIS 123A Lecture 11 Exception Handling. Introduction  Typical approach to development:  Write programs assuming things go as planned  Get ‘core’ working.
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.
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.
Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
©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.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
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.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
Exceptions Syntax, semantics, and pragmatics Exceptions1.
Exceptions Handling Exceptionally Sticky Problems.
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
Introduction to Exception Handling and Defensive Programming.
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 Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
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.
C++ Memory Overview 4 major memory segments Key differences from Java
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
Exceptions. Why exceptions? We often strive for writing portable reusable code; we are able to detect errors, however our code may be used for many different.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
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 Outline 23.1 Introduction
LECTURE LECTURE 14 Exception Handling Textbook p
Chapter 8-Exception Handling/ Robust Programming.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
Exception Handling How to handle the runtime errors.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
C++ Functions A bit of review (things we’ve covered so far)
Introduction to Exceptions in Java CS201, SW Development Methods.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Exception handling.
Exceptions Error Handling and Recovery
Chapter 16 Exception Handling
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
Exceptions.
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Overview 4 major memory segments Key differences from Java stack
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Motivation and Overview
Why exception handling in C++?
Overview 4 major memory segments Key differences from Java stack
Exceptions with Functions
Exceptions CSCE 121 J. Michael Moore
Exceptions 1 CMSC 202.
Object-Oriented Programming (OOP) Lecture No. 44
CMSC 202 Exceptions.
Exception Handling.
CMSC 202 Lesson 20 Exceptions 1.
Presentation transcript:

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 “unwinds” –Stack frame of each function in call chain “pops” –Variables in each popped frame are destroyed –Goes until an enclosing try/catch scope is reached Control passes to first matching catch block –Can handle the exception and continue from there –Can free some resources and re-throw exception

CSE 332: C++ exceptions C++ Exceptions Example Consider a program using a Number class –We’ve not covered class member functions in detail yet –Class member functions are much like “plain-old” functions –But are given a hidden extra pointer to the object (“this”) One of the class member functions is operator /= –Divides value object contains by another passed value –Problem: what if someone passes 0 to this function?

CSE 332: C++ exceptions Motivation for C++ Exceptions void Number::operator/=(const double denom) { if (denom == 0.0) { // what do we do here? } m_value /= denom; } Need to handle divide by zero case Otherwise bad things happen –Program crash –Wrong results Could set value to NaN –Special “not-a-number” value –But, caller might fail to check for it Could return a “special” value –Might be a valid return value –Could still be ignored Exceptions offer a better alternative

CSE 332: C++ exceptions C++ Exception Syntax void foo() throw (int) { throw 2; } catch (int &i) { cout << i << endl; } catch (...) { cout << “another exception” << endl; } Can throw any type Can specify what a function (only) throws in it’s declaration Can catch and use exceptions in code “Default” catch block

CSE 332: C++ exceptions What’s in a Stack Frame? In general, structure is common –A chunk of memory representing the state of an active function call –Pushed on program call stack at run-time g++ -s gives assembler output –can be used to deduce exact structure for a given platform Contains: –The previous frame pointer –The return address for the call (i.e., just after the point from which it was called) –Parameters passed to the function –Automatic (stack) variables for the function previous frame pointer return address parameters local (automatic) variables

CSE 332: C++ exceptions Illustrating the Call Stack int main (int argc, char **argv) { Number n(8.1); try { n /= 0.0; cout << n << endl; } catch (int) { return 1; } return 0; } Stack frame for function main –Pushed on program call stack –With stack variables i and c –With parameters argc and argv Note that parameters are initialized at frame creation Variables are not necessarily initialized at frame creation –May occur later in called function argcargv n m_value main

CSE 332: C++ exceptions Initializing an Object (Constructor Call) int main (int argc, char **argv) { Number n(8.1); try { n /= 0.0; cout << n << endl; } catch (int) { return 1; } return 0; } Number constructor called –Stack frame created argcargv n m_value main this Number:: Number(const double n) n

CSE 332: C++ exceptions Constructor Executes Number::Number(const double num) :m_value(n) { } Enter Number constructor –m_value is set in n How do we know which m_value to set? –Implicit this pointer argcargv n m_value main this Number::Number(const double num) num

CSE 332: C++ exceptions argcargv n m_value main Constructor Finishes Number::Number(const double num) :m_value(n) { } Return from constructor –Stack frame is popped –Return to main

CSE 332: C++ exceptions Calling Operator /= int main (int argc, char **argv) { Number n(8.1); try { n /= 0.0; cout << n << endl; } catch (int) { return 1; } return 0; } Call operator/= on n –New stack frame created –Copy 0.0 into n –Set this argcargv n m_value main this Number:: operator/=(const double denom) denom

CSE 332: C++ exceptions Exception Thrown Test denom against 0.0 –Test succeeds –throw integer 0 void Number::operator/=(const double denom) { if (denom == 0.0) { throw 0; } m_value /= denom; } argcargv n m_value main this Number::operator/=(const double denom) denom

CSE 332: C++ exceptions argcargv n m_value main Live Exception Unwinds Stack Skips over rest of function Control returns to caller Continues until try/catch scope void Number::operator/=(const double denom) { if (denom == 0.0) { throw 0; } m_value /= denom; }

CSE 332: C++ exceptions Catching the Exception int main (int argc, char **argv) { Number n(8.1); try { n /= 0.0; cout << n << endl; } catch (int) { return 1; } return 0; } We’ve reached an enclosing try/catch scope –So stack unwinding stops Control jumps to first matching catch block –Skips over intervening cout statement argcargv n m_value main

CSE 332: C++ exceptions A Few More Details try { // can throw exceptions } catch (Derived &d) { // Do something } catch (Base &d) { // Do something else } catch (...) { // Catch everything else } Control jumps to first matching catch block Order matters if multiple possible matches –Especially with inheritance- related exception classes –Put more specific catch blocks before more general ones –Put catch blocks for more derived exception classes before catch blocks for their respective base classes catch(...) –catches any type throw; –does not throw a type –essentially a call to abort()

CSE 332: C++ exceptions Exception Specifications // can throw anything void Foo::bar(); // promises not to throw void Foo::bar() throw(); // promises to only throw int void Foo::bar() throw(int); // throws only char or int void Foo::bar() throw(char,int); Make promises to the caller Allow stronger type checking enforced by the compiler By default, a function can throw anything it wants A throw clause in a function’s signature –Limits what can be thrown –A promise to calling function A throw clause with no types –Says nothing will be thrown Can list multiple types –Comma separated

CSE 332: C++ exceptions Good Programming Style with C++ Exceptions Don’t use exceptions for normal program flow –Only use where normal flow isn’t possible Don’t let exceptions leave main or constructors –Violates “normal” initialization and termination Always throw some type –So the exception can be caught Use exception specifications widely –Helps caller know possible exceptions to catch