Exceptions 1 CMSC 202.

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Advertisements

Lecture 9. 2 Exception  An exception is a unusual, often unpredictable event, detectable by software or hardware, that requires special processing occurring.
Exception Handling Introduction Try Throw Catch. Exception Handling Use exception handling to write programs that are –Clearer –More robust –More fault-tolerant.
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.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 23 - Exception Handling Outline 23.1Introduction 23.2When Exception Handling Should Be Used 23.3Other.
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.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
Rossella Lau Lecture 9, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 9: Application with Exception Handling 
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 13 - Exception Handling Outline 13.1Introduction 13.2When Exception Handling Should Be Used.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
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.
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 Outline 23.1 Introduction
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
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.
EE4E. C++ Programming Lecture 6 Advanced Topics. Contents Introduction Introduction Exception handling in C++ Exception handling in C++  An object oriented.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
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.
C++ Exceptions.
IS 0020 Program Design and Software Tools
Exceptions Error Handling and Recovery
Exceptions Exceptions are used to signal that an unexpected event has happened in a program C++ will generate exceptions for some errors in the program.
CMSC202 Computer Science II for Majors Lecture 16 – Exceptions
Chapter 14 – Exception Handling
Andy Wang Object Oriented Programming in C++ COP 3330
Exceptions, Templates, and the Standard Template Library (STL)
Why exception handling in C++?
Part IX Fundamentals of C and C++ Programming Exception Handling
EXCEPTION HANDLING.
CMSC 202 Lesson 21 Exceptions II.
Chapter 14: Exception Handling
Exceptions with Functions
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 17 Templates and Exceptions Part 2
Exception Handling and Reading / Writing Files
Exceptions 2 CMSC 202.
Exceptions and Templates
Standard Version of Starting Out with C++, 4th Edition
Lecture 11 Objectives Learn what an exception is.
Exceptions, Templates, and the Standard Template Library (STL)
Object-Oriented Programming (OOP) Lecture No. 43
Object-Oriented Programming (OOP) Lecture No. 44
Department of Computer and Information Science, School of Science, IUPUI Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI
Lecture 9.
Exceptions for safe programming.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
CMSC 202 Lesson 20 Exceptions 1.
More C++ Concepts Exception Handling Templates.
Presentation transcript:

Exceptions 1 CMSC 202

Warmup // A in Foo! // Error! // A in Bar! // Error! // B in Bar! class A { public: virtual void Foo( ) { cout << "A in Foo!" << endl; } void Bar( ) { cout << "A in Bar!" << endl; } protected: int val; }; class B : public A { cout << "B in Bar!" << endl; } int main ( ) { A *a1 = new B; a1->Foo(); B *b1 = new A; b1->Foo(); A *a2 = new B; a2->Bar(); B b2; cout << b2.val; B *b3 = new B; b3->Bar(); B b4; b4.Bar(); return 0; } // A in Foo! // Error! // A in Bar! // Error! // B in Bar! // B in Bar!

Common Errors (Runtime) Memory allocation error when using new File open error Out of bounds array subscript Division by zero Function PreConditions not met

Error Handling Techniques assert (condition) if the condition is false, the program terminates Ignore the error or try to handle the error internally devastating for real products, but maybe okay for your own software Set an indicator for other code to detect (e.g., return a flag) Issue an error message and exit

Error Handling, Currently Commonly, error handling is interspersed Advantage Error processing close to error Disadvantage Code cluttered from error processing Application cannot handle error as it wants to Layering, Encapsulation Low-level code should not process errors Low-level code should alert high-level code High-level code should handle errors

Fundamental Issue Class user may handle error in any way Exit program Output message & continue Retry function Ask user what to do … Class implementer can’t know which the user of class wants

Exception Handling New Strategy Positives Low-level code detects error “Throws” error to higher level code High-level code processes error Positives Code that caused error loses control Catch all kinds of errors Usually used in recoverable situations

Exception Syntax Three primary components: Try/catch block // some code to try } catch (ObjectType& obj) { // handle the error, if any Throwing an exception throw ObjectType(parameters); Specifying which exceptions a function throws void funcName(parameter) throw ObjectType { }

Simple Throw double quotient(int num, int den) { if (den == 0) throw “Error: Divide by Zero”; return static_cast<double>(num) / den; } int main() try cout << quotient(7, 0) << endl; catch (string& e) cout << e << endl; return 0;

Throwing an Exception class DivByZeroEx { public: DivByZeroEx ( ) : m_message ("divide by 0") { /* no code */ } const string& what ( ) const { return m_message; } private: const string m_message; }; double quotient(int num, int den) if (den == 0) throw DivByZeroEx(); return static_cast<double>(num) / den; }

Catching an Exception int main() { int numerator, denominator; double result; cout << "Input numerator and denominator" << endl; cin >> numerator >> denominator; try { result = quotient(numerator, denominator); cout << "The quotient is: " << result << endl; } catch (DivByZeroEx& ex) { // exception handler cerr << "Exception occurred: " << ex.what() << endl; // code continues here return 0;

Multiple Catch Blocks…Yes! try { // code that might throw an exception } catch (ExceptionObject1& ex1) // exception handler code . . . catch (ExceptionObject2& ex2) catch (ExceptionObjectN& exN) catch (...) // default exception handler code Most Specific Multiple catch blocks – catch different types of exceptions! What’s this? “Catch Everything Else” Least Specific

Nested Functions? // function2 throws an exception void function2( ) { cout << "function2" << endl; throw int(42); } // function1 calls function2, // but with no try/catch void function1( ) function2( ); cout << "function1" << endl; // main calls function1, // with try/catch int main( ) { try { function1( ); } catch (int) cout << "Exception “ << “occurred" << endl; return 0; Stack is unwound until something catches the exception OR until unwinding passes main What happens then?

Rethrowing Exceptions What if current scope shouldn’t/can’t handle error? Re-throw error to next scope up the stack try { // code that could throw an exception } catch (someException &e){ throw; // rethrow the exception to the next } // enclosing try block

Rethrow Example Application program // handles exception if full Add item to inventory // rethrows exception if full Insert item in list Is list full? // throws exception if full How might we have used this in one of our past projects?

Practice Write a function to Sort a vector of integers If the vector has no elements Throw an exception Use the message “Error: The vector is empty” Write a main function that will: Create a vector Catch the error

Challenge Create an inheritance hierarchy for Exceptions Base class: Exception Derived classes DivideByZero FileNotFound Keep them simple – each only has a string message Write two functions that throw each exception Write a main that catches each exception properly