CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.

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.
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.
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.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 CSC241: Object Oriented Programming Lecture No 28.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
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
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
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.
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.
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.
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 23 - Exception Handling Outline 23.1Introduction.
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.
Exception Handling Outline 23.1 Introduction
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
LECTURE LECTURE 14 Exception Handling Textbook p
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.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
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.
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 in C++
Exceptions Error Handling and Recovery
Chapter 16 Exception Handling
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
CS212: Object Oriented Analysis and Design
Exceptions.
CMSC202 Computer Science II for Majors Lecture 16 – 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
Why exception handling in C++?
Chapter 14: Exception Handling
Overview 4 major memory segments Key differences from Java stack
Exceptions with Functions
Throwing and catching exceptions
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++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements introduce scopes, e.g., of (temporary) variables A (useful) statement usually has a side effect –Stores a value for future use: j = i + 5; –Performs input or output: cout << j << endl; –Directs control flow: if (j > 0) {…} else {…} –Interrupts control flow: throw out_of_range; –Resumes control flow: catch (RangeError &re) {…} goto considered too low-level –Usually better to use break or continue –If you have to use goto, you must comment why

CSE 332: C++ Statements Motivation for C++ Exception Statements void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value /= denom; } Need to handle cases where program cannot behave normally –E.g., zero denominator for division Otherwise bad things happen –Program crashes –Wrong results Could set value to Number::NaN –I.e., a special “not-a-number” value –Must avoid using a valid value… … which may be difficult (e.g., for int) –Anyway, caller might fail to check for it Exceptions offer a better alternative

CSE 332: C++ Statements C++ Exceptions: Throw Statement Syntax void foo() { throw 2; } try { foo(); } catch (int &i) { cout << “caught ” << i << endl; } catch (...) { cout << “another exception” << endl; } Can throw any type Can catch, inspect, use, refine, rethrow exceptions –By value makes local copy –By reference allows modifications to be made to the original exception itself “Default” catch block is indicated by three dots –Catches every type

CSE 332: C++ Statements C++11 Library Exception Hierarchy C++11 standardizes a hierarchy of exception classes –To access these classes #include Two main kinds (subclasses) of exception –Run time errors (overflow errors and underflow errors) –Logic errors (invalid arguments, length error, out of range) Several other useful subclasses of exception –Bad memory allocation –Bad cast –Bad type id –Bad exception You can also declare other subclasses of these –Using the class and inheritance material in later lectures

CSE 332: C++ Statements C++ Exceptions Interrupt Control Flow 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 –This goes on until a matching 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 Let’s look at the call stack and how it behaves –Good way to explain how exceptions work (in some detail) –Also a good way to understand normal function behavior

CSE 332: C++ Statements Exceptions Manipulate the Function Call Stack In general, the call stack’s structure is fairly basic –A chunk of memory representing the state of an active function call –Pushed on program call stack at run-time (can observe in a debugger) g++ -s  generates machine code (in assembly language) –A similar feature can give exact structure for most platforms/compilers Each stack frame contains: –A pointer to the previous stack frame –The return address (i.e., just after point from which function was called) –The parameters passed to the function (if any) –Automatic (local) variables for the function Sometimes called “stack variables” previous frame pointer return address parameters automatic variables

CSE 332: C++ Statements Illustrating the Call Stack (1/8) enum results {success, failure}; int main (int, const char *[]) { Number n(8.1); try { n /= 0.0; cout << n << endl; } catch (int) { return failure; } return success; } Stack frame for function main –Pushed on program call stack –With stack variable n –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 n m_value main

CSE 332: C++ Statements Illustrating the Call Stack (2/8) int main (int, const char *[]) { Number n(8.1); try { n /= 0.0; cout << n << endl; } catch (int) { return failure; } return success; } Number constructor called –Stack frame created –Implicit this pointer points to object in previous stack frame n m_value main this Number::Number(const double d) d

CSE 332: C++ Statements Illustrating the Call Stack (3/8) Number::Number(const double d) :m_value(d) { } Enter Number constructor –m_value is set in object How do we know which m_value to set? –Implicit this pointer n m_value main this Number::Number(const double d) d

CSE 332: C++ Statements n m_value main Illustrating the Call Stack (4/8) Number::Number(const double d) :m_value(d) { } Return from constructor –Its stack frame is popped –Returns to main

CSE 332: C++ Statements Illustrating the Call Stack (5/8) int main (int, const char *[]) { Number n(8.1); try { n /= 0.0; cout << n << endl; } catch (int) { return failure; } return success; } Call operator/= on n –New stack frame created –Copy 0.0 into call as denom –Set this n m_value main this Number::operator/=(const double denom) denom

CSE 332: C++ Statements Illustrating the Call Stack (6/8) 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; } n m_value main this Number::operator/=(const double denom) denom

CSE 332: C++ Statements n m_value main Illustrating the Call Stack (7/8) throw unwinds call stack Skips over rest of function Returns to caller void Number::operator/=(const double denom) { if (denom == 0.0) { throw 0; } value_ /= denom; }

CSE 332: C++ Statements Illustrating the Call Stack (8/8) int main (int, const char *[]) { Number n(8.1); try { n /= 0.0; cout << n << endl; } catch (int) { return failure; } return success; } We’ve reached an enclosing try/catch scope –And catch expression matches –So stack unwinding stops Control jumps to first matching catch block –Skips over intervening cout statement (no output!) n m_value main

CSE 332: C++ Statements More Details About Catching Exceptions in C++ 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

CSE 332: C++ Statements More About Catching Exceptions in C++ try { // can throw exceptions } catch (Derived &d) { // Do something } catch (Base &d) { // Do something else } catch (...) { // Catch anything else, // do as much as you can throw; // rethrows it } catch(...) –“Catch-all” handler, catches any type –Often should at least free resources, generate an error message, etc. –May rethrow exception for another handler to catch and do more throw; –As of C++11 standard, rethrows a caught exception (very useful in Catch-all handlers )

CSE 332: C++ Statements Exception Specifications (do not use them) // can throw anything void Foo::baz(); // promises not to throw void Foo::baz() throw(); // promises to only throw int void Foo::baz() throw(int); // only char or int void Foo::baz() throw(char,int); Added in C++98, deprecated in C++11 –Replaced with noexcept Make promises to the calling function –Empty throw clause promises no exceptions –Can list multiple types (comma separated) By default, a function can throw whatever it wants –Throw clause limits what function body can throw –But may call code that leaves off throw clause

CSE 332: C++ Statements Rules of Thumb for Using C++ Exceptions Use exceptions to handle any cases where the program cannot behave normally –Do not use exceptions as a way to control program execution under normal operating conditions Don't let a thrown exception propagate out of the main function uncaught –Instead, always catch any exceptions that propagate up –Then return a non-zero value to indicate program failure Don’t rely on exception specifications –May be a false promise, unless you have fully checked all the code used to implement that interface –No guarantees that they will work for templates, because a template parameter could leave them off and then throw