Exceptions handling Try, catch blocks Throwing exceptions.

Slides:



Advertisements
Similar presentations
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Advertisements

Yoshi
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: 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.
CSIS 123A Lecture 11 Exception Handling. Introduction  Typical approach to development:  Write programs assuming things go as planned  Get ‘core’ working.
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.
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.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  due to poor understanding of the problem and solution.
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.
SNU OOPSLA Lab. 14. Exception Handling © copyright 2001 SNU OOPSLA Lab.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
1 CSC241: Object Oriented Programming Lecture No 27.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
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.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
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. 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.
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.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception Handling Outline 23.1 Introduction
LECTURE LECTURE 14 Exception Handling Textbook p
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.
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.
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.
Java Exceptions a quick review….
Chapter 16 Exception Handling
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
CMSC202 Computer Science II for Majors Lecture 16 – Exceptions
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Exceptions David Rabinowitz.
Exceptions In this lecture:
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Chapter 10 – Exception Handling
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Why exception handling in C++?
EXCEPTION HANDLING.
CMSC 202 Lesson 21 Exceptions II.
Chapter 14: Exception Handling
Chapter 17 Templates and Exceptions Part 2
Chapter 12 Exception Handling and Text IO
Exception Handling CSCI293 - C# October 3, 2005.
Exceptions 2 CMSC 202.
Advanced C++ Exception Handling
Exceptions CSCE 121 J. Michael Moore
Web Design & Development Lecture 7
CSC 270 – Survey of Programming Languages
Exceptions 1 CMSC 202.
Exceptions handling Try, catch blocks Throwing exceptions.
Interrupts Hardware Software.
Exceptions handling Try, catch blocks Throwing exceptions.
Object-Oriented Programming (OOP) Lecture No. 44
Lecture 9.
Java Basics Exception Handling.
CMSC 202 Exceptions.
Exception Handling.
Exceptions.
CMSC 202 Lesson 20 Exceptions 1.
More C++ Concepts Exception Handling Templates.
Presentation transcript:

Exceptions handling Try, catch blocks Throwing exceptions. Exceptions in C++ Exceptions handling Try, catch blocks Throwing exceptions.

What is an Exception? An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Example (file not found) void readFile() { openInput = open(“input.txt”); strings[] s = readFrom(openFile); doStuff(s); close(openFile); } Should work fine, however, what if the file input.txt is not there one day when you are running this program?

3 kinds of exceptions 1) Checked exceptions. User can anticipate Ex) file not found. 2) Error exceptions. Error that are external to the applications like hardware exceptions. 3) Runtime exception. Logic error in code and improper used of API, etc.

Class definitions for exception objects Consider the following : The Mathematical exception library might be organized like this. class Matherr { virtual void debug_print( ) const { cerr << “Math error”;} } ; class Overflow : public Matherr { } ; class Underflow : public Matherr { } ; class Zerodevide: public Matherr { } ; class overflow : public Matherr const char* op; int a1, a2: public: void int_overflow(const char* p, int a, int b) { op = p;a1= x; a2 = y;} virtual void debug_print( ) const { cerr << op << ‘(‘ << a1 << ‘,’ << a2 << ‘)’; }

Catching exceptions void f( ) { try { // some math code goes here } catch (Overflow) { // code to handle an over flow catch(Matherr) { // Handle any Matherr that is not an overflow catch(Dividezero) { // Handle any Divide by zero catch(…) { // Handle any exception not listed above Comments: the Dividezero will never run because Dividezero is a Matherr catch(…) will catch any exception object

Catch by reference/pointer void f( ) { try { g( ); // g( ) throws an Int_overflow exception } catch(Matherr& m) { m.debug_print( ); } Since the exception object was caught by reference Int_overflow::debug_print is called. If caught by value, then Matherr::debug_print would have been called.

Throwing Exceptions (intentionally) class DivideByZero { public: double divisor; DivideByZero(double x) { divisor = x}| ; }; … int divide(int x, int y) if(y==0) { throw DivideByZero(x); } } try { divide(12, 0); catch (DivideByZero divZero) cerr<<"Attempted to divide "<<divZero.divisor<<" by zero"; cout << “moving right along”

Exceptions are Thread Safe C++ exception handling is thread safe. Throwing on one thread (including rethrow) has no impact on any throw/catch in progress on another thread.

Exceptions and Destructors void readBook(istream& book) { while(book) page *pp = readBook(book); pp->readPage(); delete pp; } What if readPage throws and exception?

Consider this solution void readBook(istream& book) { while(book) page *pp = readBook(book); try { pp->readPage(); } catch(…) { delete pp; throw; } delete pp; } Works but, we have to pepper our code with try catches.

Auto_pointers (a.k.a Smart Pointers) template<class T> class AUTO_PTR { public: typedef T element_type; explicit AUTO_PTR(T *pVal = 0) throw() { if (pVal) {m_AutoPtr = pVal} else {m_AutoPtr = 0;} AUTO_PTR(const ATUO_PTR<T>& ptrCopy throw() { if (ptrCopy) {m_AutoPtr = ptrCopy} else {m_AutoPtr = 0;} AUTO_PTR<T>& operator=(AUTO_PTR& ptrCopy) throw() { if (ptrCopy) { m_AutoPtr = &ptrCopy} else {m_AutoPtr = 0; } return m_AutoPtr; } ~AUTO_PTR() { if (m_AutoPtr) { delete m_AutoPtr; } } T& operator*() const throw() { return *m_AutoPtr; } T& *operator->() const throw() { return m_AutoPtr; } T& *get() const throw() { return *m_AutoPtr; } Private: T *m_AutoPtr; };

Original code with auto_ptr { while(book) auto_ptr<page> *pp = readBook(book); pp->readPage(); // delete pp; }

Side fact about C++ delete of pointers C++ guarantees that: delete p; // delete the object p points to Will be safe if p currently is null. That is, you will not be deleting part of the operating system, instead no action will be taken.

Exceptions during Constructer MyMovies::MyMovies { popcorn_ptr = new popcorn(); movie_ptr = new movie(bigMovie); soda_ptr = new soda(); } If there is an exception thrown during the creating of the bigMovie, should this MyMovie object be destroyed? Should the entire destructor run during destruction?

C++ destroys constructed objects C++ only destroys fully constructed objects. There is no way to know how much of the destructor to run for a partially constructed object. So, we would want the objects to be either fully constructed or not constructed at all

Consider this solution MyMovies::MyMovies { popcorn = new popcorn(); try { movie = new movie(bigMovie); } catch(…) { delete popcorn; throw; } try { soda = new soda(); } catch(…) { delete popcorn; delete movie; throw; } } If a step doesn’t go well, undo everything done before it. This code duplicates the destructor. It might make sense to put the common code in private functions and have the constructors and destructors call them.

Add constant pointers to the problem Suppose class designer wants the pointers to the objects are constant. Constant pointers can only be initialized in an initialization list. They can not be done in a constructor body.

Consider another solution MyMovies::MyMovies( const popcorn& p, const movie& m, const soda& s) : popcorn_ptr(p != “” ? new popcorn() : 0); movie_ptr(m != “” ? new movie() : 0); soda_ptr(s != “” ? new soda() : 0); { } private: auto_ptr<popcorn> popcorn; auto_ptr<movie> movie_ptr; auto_ptr<soda> soda_ptr;

Exceptions during exception handling If a program throws an exception and during that exception handling, another exception is thrown, what should the operating system do? Ignore the second exception and continue handling the first. Abandon the first exception handler and handle the second one. Run the second exception handler and then return to the first. Completely give up and call “terminate”.

Don’t throw exception from destructors During exception handling, all objects that are completely constructed will be destructed after the code in the exception handler runs. This is part of exception handling. What if one of your many destructors throws an exception which your destructor catches? Answer: If the destructor ran as part of normal processing, your exception handler will run. If it ran during some exception handling, then it will cause “terminate” to run and therefore all other objects that need to be destroyed after yours will not be destroyed (memory leak)

Exception object’s types C++ specifies that an object thrown as an exception is always copied. This copying happens even if the object type is not in danger of being deleted (static, heap, etc. ) They are copied as the static type of the receiving object.

throw vs. throw e ... Catch (MathError& ME) { throw; // throws exception of whatever type came in } vs. throw ME; // throws exception of type MathError

throw() in the exception specification void func() // may throw any exception void gunc() throw(A,B) { } // only throws A and B void hunc() throw() { } // doesn’t throw any exception void junc() throw () // claims to throw nothing but… { func() ; // …it may throw anything }