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.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 18 Exception Handling. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Exception Handling Basics Defining.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
1 Week 11 l Basic Exception Handling »the mechanics of exceptions l Defining and Using Exceptions »some "simple" cases l Reality Check »guidelines for.
Review Linked list: Doubly linked list, insertback, insertbefore Remove Search.
1 Handling Exceptions COSC 1567 C++ Programming Lecture 11.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
Exception Handling Chapter 8. Outline Basic Exception Handling Defining Exception Classes Using Exception Classes.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
1 Problem Solving with C++ The Object of Programming Walter Savitch Chapter 16 Exception Handling Slides by David B. Teague, Western Carolina University,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
Chapter 9 Exception Handling Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Chapter 81 Exception Handling Chapter 8. 2 Reminders Project 5 due Oct 10:30 pm Project 3 regrades due by midnight tonight Discussion groups now.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
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.
Java Exception Handling
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
Exceptions COMPSCI 105 S Principles of Computer 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.
Object Oriented Programming
Handling ErrorstMyn1 Handling Errors Up to this point we haven't worried much about errors or exceptions. First, let's distinguish between errors and exceptions.
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.
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
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.
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.
Exception Handling Fall 2008 Dr. David A. Gaitros
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
LECTURE LECTURE 14 Exception Handling Textbook p
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
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.
Asif Nawaz University Institute of Information Technology, PMAS-AAUR Lecture 05: Object Oriented Programming:2014 Object-Oriented Programming in C++ Exception.
Exception Handling C++.
Chapter 16 Exception Handling
Exceptions.
CMSC202 Computer Science II for Majors Lecture 16 – Exceptions
Andy Wang Object Oriented Programming in C++ COP 3330
Exceptions, Templates, and the Standard Template Library (STL)
Why exception handling in C++?
Exception Handling Chapter 9.
Andy Wang Object Oriented Programming in C++ COP 3330
Exception Handling Chapter 9 Edited by JJ.
Exceptions and Templates
Exceptions CSCE 121 J. Michael Moore
Standard Version of Starting Out with C++, 4th Edition
Exceptions, Templates, and the Standard Template Library (STL)
Exceptions for safe programming.
CMSC 202 Exceptions.
Presentation transcript:

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 circumstance that the section of code containing the problem is not explicitly designed to handle. Exception handling is useful because it makes it easy to separate the error handling code from the code written to handle the chores of the program. Doing so also makes reading and writing the code easier As a programmer, you should anticipate any abnormal behavior that could be caused by the user entering wrong information that could otherwise lead to unpredictable results.

An Exception Example Imagine: people rarely run out of milk: cout > donuts; cout > milk dpg = (double)donuts/double(milk); cout << donuts << "donuts.\n"; << milk << "glasses of milk.\n"; << "You have " << dpg << "donuts for each glass of milk.\n"; Basic code assumes never run out of milk

An Exception Example However, if one day you run out of milk, i.e. milk=0, then the following line of code has an issue dpg = (double)donuts/double(milk); // divided by zero! Program should accommodate unlikely situation of running out of milk – Can use simple if-else structure: if (milk <= 0) cout << "Go buy some milk!\n"; else {…} Notice: this is NOT an exception-handling, because it is in the regular part of the program!

Toy Example with Exception Handling: Display Copyright © 2010 Pearson Addison-Wesley. All rights reserved. Exception Handling cout <<“…”; cin >> donuts; cout << “…”; cin >> milk; if (milk <=0) cout << “Go buy some milk!” <<endl; else { … } … Not an exception handling!

Toy Example Discussion Code between keywords try and catch – Same code from ordinary version, except if statement simpler: if (milk <= 0) throw donuts; – Much cleaner code – If "no milk"  do something exceptional The "something exceptional" is provided after keyword catch 18-6 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Toy Example try-catch Try block – Handles "normal" situation Catch block – Handles "exceptional" situations Provides separation of normal from exceptional – Not big deal for this simple example, but important concept 18-7 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

try block Basic method of exception-handling is try-throw-catch Try block: try { Some_Code; } – Contains code for basic algorithm when all goes smoothly 18-8 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

throw Inside try-block, when something unusual happens: try { Code_To_Try if (exceptional_happened) throw donuts; More_Code… } – Keyword throw followed by exception type – Called "throwing an exception" 18-9 Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

catch-block When something thrown  goes somewhere – In C++, flow of control goes from try-block to catch-block try-block is "exited" and control passes to catch-block – Executing catch block called "catching the exception" Exceptions must be "handled" in some catch block Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

cout <<“…”; cin >> donuts; cout << “…”; cin >> milk; if (milk <=0) cout << “Go buy some milk!” <<endl; else { … } More_code … // will be executed Not an exception handling! Exception Handling try { cout <<“…”; cin >> donuts; cout << “…”; cin >> milk; if (milk <=0) throw donuts; else { … } More_code … // will NOT be executed } catch (int e) { cout << “Go buy some milk!” <<endl; }

catch-block More Recall: catch(int e) { cout << e << " donuts, and no milk!\n"; << " Go buy some milk.\n"; } Looks like function definition with int parameter! – Not a function, but works similarly – throw is like a "function call" Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

catch-block Parameter Recall: catch(int e) "e" called catch-block parameter, i.e. type of the errors – Each catch block can have at most ONE catch-block parameter Does two things: 1.type name specifies what kind of thrown value the catch-block can catch 2.Provides name for thrown value caught; can "do things" with value Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Show examples

Defining Exception Classes throw statement can throw value of any type Exception class – Contains objects with information to be thrown – Can have different types identifying each possible exceptional situation – Still just a class An "exception class" due to how it’s used Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Exception Class for Toy Example Consider: class NoMilk { public: NoMilk() { } NoMilk(int howMany) : count(howMany) { } int getcount() const { return count; } private: int count; }; throw NoMilk(donuts); – Invokes constructor of NoMilk class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Trivial Exception Classes Consider: class DivideByZero { }; No member variables No member functions (except default constructor) Nothing but it’s name, which is enough – Might be "nothing to do" with exception value – Used simply to "get to" catch block – Can omit catch block parameter Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Show examples

Multiple Throws and Catches try-block typically throws any number of exception values, of differing types, at different places Of course only one exception thrown – Since throw statement ends try-block But different types can be thrown – Each catch block only catches "one type" – Typical to place many catch-blocks after each try-block To catch "all-possible" exceptions to be thrown Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Catching Order of catch blocks important – More specific exception types go first! Catch-blocks tried "in order" after try-block – First match handles it! Be careful the inheritance relation between different exception classes! Consider: catch (…) { } – Called "catch-all", "default" exception handler – Catches any exception – Ensure catch-all placed AFTER more specific exceptions! Or others will never be caught! Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Throwing Exception in Function Function might throw exception Callers might have different "reactions" – Some might desire to "end program" – Some might continue, or do something else Makes sense to "catch" exception in calling function’s try-catch-block – Place call inside try-block – Handle in catch-block after try-block Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Throwing Exception in Function Example Consider: try { quotient = safeDivide(num, den); } catch (DivideByZero) { … } safeDivide() function throws DividebyZero exception – Handled back in caller’s catch-block Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Show the example of throwing exception inside a function

Preferred throw-catch Triad: throw void functionA() throw (MyException) { … throw MyException(arg); … } Function throws exception as needed Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Preferred throw-catch Triad: catch Then some other function: void functionB() { … try { … functionA(); … } catch (MyException e) { // Handle exception } … } Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Uncaught Exceptions Should catch every exception thrown If not  program terminates – terminate() is called Recall for functions – If exception not in throw list: unexpected() is called It in turn calls terminate() So same result Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Overuse of Exceptions Exceptions alter flow of control – Similar to old "goto" construct – "Unrestricted" flow of control Should be used sparingly Good rule: – If desire a "throw": consider how to write program without throw – If alternative reasonable  do it Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Summary 1 Exception handling allows separation of "normal" cases and "exceptional" cases Exceptions thrown in try-block – Or within a function whose call is in try-block Exceptions caught in catch-block try-blocks typically followed by more than one catch-block – List more specific exceptions first Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Summary 2 Best used with separate functions – Especially considering callers might handle differently Exceptions thrown in but not caught in function, should be listed in throw list Exceptions thrown but never caught  program terminates Resist overuse of exceptions – Unrestricted flow of control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

What is the output of the following program under the given input? class DivideExp { public: DivideExp(double in=0) : divisor (in) {} double divisor; }; class DivideByZero : public DivideExp { public: DivideByZero(double in=0) : DivideExp(in) {} }; class DivideByNeg: public DivideExp { public: DivideByNeg(double in=0) : DivideExp(in) {} }; void main() { try { cout <<“input num1:”; cin >> num1; cout << “input num2: ”; cin >> num2; if (num2 == 0) throw DivideByZero(num1); else if (num2 < 0) throw DivideByNeg(num1); else { cout <<“num1/num2=“<<num1/num2<<endl; } cout << “succeeded!” << endl; } catch (DivideByZero e) { cout << e.divisor << “divided by zero!” <<endl; } catch (DivideExp e) { cout << e.divisor << “divided by invalid value!”<<endl; } catch (DivideByNeg e) { cout << e.divisor << “divided by negative value!”<<endl; } catch (…) { cout << “Unknown exception!” << endl; } input 1: 4, 2 input 2: 5, 0 input 3: 0, -1

What is the output of the following program under the given input? class DivideExp { public: DivideExp(double in=0) : divisor (in) {} double divisor; }; class DivideByZero : public DivideExp { public: DivideByZero(double in=0) : DivideExp(in) {} }; class DivideByNeg: public DivideExp { public: DivideByNeg(double in=0) : DivideExp(in) {} }; void main() { try { cout <<“input num1:”; cin >> num1; cout << “input num2: ”; cin >> num2; if (num2 == 0) throw DivideByZero(num1); else if (num2 < 0) throw DivideByNeg(num1); else { cout <<“num1/num2=“<<num1/num2<<endl; } cout << “succeeded!” << endl; } catch (DivideByZero e) { cout << e.divisor << “divided by zero!” <<endl; } catch (DivideExp e) { cout << e.divisor << “divided by invalid value!”<<endl; } catch (DivideByNeg e) { cout << e.divisor << “divided by negative value!”<<endl; } catch (…) { cout << “Unknown exception!” << endl; } succeeded! 5 divided by zero! 0 divided by invalid value!