Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

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.
CS102--Object Oriented Programming
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.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
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.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 7: Errors 1 Based on slides created by Bjarne Stroustrup.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  due to poor understanding of the problem and solution.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
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:
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
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
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
1 CSC241: Object Oriented Programming Lecture No 27.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
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.
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
Testing and Debugging Version 1.0. All kinds of things can go wrong when you are developing a program. The compiler discovers syntax errors in your code.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
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.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions and Program Correctness based on the original work by Dr. Roger deBry Version 1.1.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Chapter 8-Exception Handling/ Robust Programming.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Exception Handling How to handle the runtime errors.
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
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.
Exceptions.
CMSC202 Computer Science II for Majors Lecture 16 – Exceptions
Why exception handling in C++?
Chapter 14: Exception Handling
Exception Handling Chapter 9.
Exceptions with Functions
Exception Handling Chapter 9 Edited by JJ.
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exceptions 10-May-19.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

Exceptions

Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use exceptions Explain the rules for exception handling and exception

Motivation Consider the following case. A programmer writes a program, using a library function fnc( ). Function fnc( ) encounters a situation that it cannot handle. The function fnc( ) is capable of detecting the situation, but does not know anything about the program in which it was imbedded, so does not know how to handle it. What should the function do?

The function has several choices: It can terminate the program. This could be very bad in a program that cannot afford to crash. It can leave the state of the data used in the program in a complete mess, or otherwise cause serious harm. Rule of thumb: functions should not terminate the program! Would you want to be on a spacecraft when a method calculating your re-entry path caused the navigational program to terminate?

It can return an error value. Two problems occur with this approach. 1. The function may already return valid data values, and an invalid value does not exist to signal an error. 2. If an error code is returned, then the checking of return values at all levels of the program becomes very tedious. This is common behavior in C programs, where there is no built-in exception handling. It can create “spaghetti” code.

It can return some value, but leave the program in an error state. This may be the worst situation, since the user does not know that an error occurred. Meanwhile, the program has done something wrong and no one knows.

The C++ exception mechanism is meant to handle exceptional situations … that is, situations where some part of the program could not do what it was supposed to do for some reason. The important idea in exception handling is that the code that discovers the exception condition is not necessarily responsible for handling the exception. It can push the exception up the through the sequence of callers until it reaches a point where there is sufficient information about the context in which the program is running to resolve the problem.

Well written functions are very independent of surrounding code. Method Work input output

Example main ( ) user interface code calculation code file manager code start a dialogue with end user * get some data * get a file name call a function to do some calculations with the data open a file and save the result of the calculations This function does not know that any calculations were done or where the file name came from. This function knows nothing about files or filenames This function, if it knew that the filename was wrong, could ask the user for a different name.

Example

// getValueAt method int getValueAt(vector theVector, int i) { return theVector[ i ]; } Suppose we have this function that returns the integer value at index i of some vector.

int main( ) { vector data; int inputValue = 0; // some code here to fill the vector // show value at a given index do { cout << "\nGive me an index and I'll show you what number is there."; cout << "\nEnter a -1 to stop."; cin >> inputValue; if (inputValue != -1) cout << "\nthe value at index " << inputValue << " is " << getValueAt(data, inputValue); cout << endl; } while (inputValue != -1); system("PAUSE"); return 0; } And suppose main( ) contains this code … What happens when the user enters an index of 5 and the vector only contains 3 numbers?

We will do several things to fix this problem. 1.We will create an exception class. 2. We will put a test in the getValueAt( ) method to test the index. If it is out of range, we will throw an exception. 3. In main( ), we will put the call to the getValueAt( ) method in a try block. 4. We will write a catch block in main( ) to handle the exception.

An Exception Class We use objects of our own exception class to report an exception. It is common for the exception class to contain data members that help to identify the problem, and functions to get that data from the object.

class BadIndexException { private: int theIndex; public: BadIndexException(int i) { theIndex = i; } int getTheIndex( ) const { return theIndex; } }; give the exception class a meaningful name A data member to hold the bad index The constructor saves the bad index A function to get the bad index

int getValueAt(vector theVector, int index) { if (index >= theVector.size( ) ) { throw BadIndexException(index); } else return theVector[index]; } If index is greater than the size attribute of the vector then we would get an out of bounds exception. But inside this method, we don’t have enough context to solve the problem, so create an object of the exception class, and pass it back to the calling method. When an exception is thrown, execution of the method stops immediately and control returns to the calling point with the exception object saved on the stack.

do { cout << "\nGive me an index and I'll show you what number is there."; cout << "\nEnter a -1 to stop."; cin >> inputValue; if (inputValue != -1) try { int num = getValue(data, inputValue); cout << "\nthe value is " << num; } catch(BadIndexException &e) { cout << "\nThe index " << e.getTheIndex( ) << " is out of range, try again."; } cout << endl; } while (inputValue != -1); Place any code where you expect that an exception may occur inside of a try block. Also include in the try block any statements you want skipped, should an exception occur. If no exception occurs, control proceeds to the first statement after the catch block.

do { cout << "\nGive me an index and I'll show you what number is there."; cout << "\nEnter a -1 to stop."; cin >> inputValue; if (inputValue != -1) try { int num = getValue(data, inputValue); cout << "\nthe value " is " << num; } catch(BadIndexException e) { cout << "\nThe index " << e.getTheIndex( ) << " is out of range, try again."; } cout << endl; } while (inputValue != -1); The catch block must immediately follow the try block. If an exception of the type given as a parameter is received by the calling method, then this catch block is executed. Otherwise, it is not. After the catch blocl executes control proceeds to the first statement after the catch block.

The standard library in C++ contains a number of built in exception classes. If the exception condition that you are dealing with fits one of these standard exception classes, then you can use that built in exception class instead of creating your own. Built In Exception Classes

Multiple Exceptions When a function executes, it may be possible that more than one kind of an exception may occur. C++provides a mechanism for the calling method to figure out which exception occurred.

try { cout << "\nthe value is " << getValueAt(data, inputValue); } catch(EmptyVectorException e) { cout << e.getMessage( ); } catch(BadIndexException e) { cout << "\nThe index " << e.getTheIndex( ) << " is out of range, try again."; } cout << endl; Multiple things can go wrong inside this try block The user may enter an invalid index The vector may be empty

So we need two catch blocks, one right after the other. Each takes as its parameter the type of exception it will handle. Only the catch block matching the type of exception thrown will be executed. The other catch block(s) will be skipped. try { cout << "\nthe value is " << getValueAt(data, inputValue); } catch(EmptyVectorException e) { cout << e.getMessage( ); } catch(BadIndexException e) { cout << "\nThe index " << e.getTheIndex( ) << " is out of range, try again."; } cout << endl;

catch(EmptyVectorException e) { cout << e.getMessage( ); } catch(BadIndexException e) { cout << "\nThe index " << e.getTheIndex( ) << " is out of range, try again."; } catch(...) { cout << "\nUnknown error..."; } The default catch (…) will catch any type of exception

If an exception is not caught, your program will terminate and the stack trace will be displayed.

Catch Rules The catch block that is executed is the first catch block following the currently active try block, whose parameter matches the type thrown. The default catch catch (…) will catch any exception type thrown. If no match is found, the program is terminated.

Re-throwing an exception Suppose that a function catches an exception, but the catch block cannot completely handle the error. It can re-throw the exception, causing it to flow to the code that called this function. throw;

Sometimes called stack unwinding, exception propagation works as follows: If an exception is not handled where it occurs, All of the local variables in the called function are destroyed The function immediately exits and the uncaught exception is raised in (passed to) the calling function. Control returns to the point where the call was made If the call was inside of a try block, an attempt is made to catch the exception - If a matching catch block is found, it is executed - If no match is found, control passes to the calling function, using this same mechanism. If the calling code is not inside of a try block, control passes to the calling function, using this same mechanism. Exception Propagation

int main ( ) { try { function1 ( ); cout << “\nIt worked!!”; } catch(Exception e ) { cout << “Exception occurred… didn’t work!”; } return 0; }

void function1 ( ) { cout << “Starting function 1 … ”; system(“PAUSE”); cout << calling function2“; function2( ); cout << “you won’t see this message!”; }

void function2 ( ) { cout << “Starting function2 … “; system(“PAUSE”); cout << “Calling function3“; function3 ( ); cout << “you won’t see this message!”; }

void function3 ( ) { cout << “Starting Method3 … press a key” << endl; system(“PAUSE”); cout << “Whoa baby” << endl; throw (new Exception(“Thrown in function 3”) ); }

main ( ) { try { function1( ); } catch { }... void function1 ( ) { function2 ( ) … void function2 ( ) { function3( ) … void function3 ( ) { throw exception;... exception Stack rtn addressm rtn address1 rtn address2 exception Now find the right catch block!

Stream Exceptions As you have seen, failing I/O operations do not automatically generate exceptions. However, if want to use exceptions to handle I/O problems You can write cout.exceptions(ios_base::badbit | ios_base::failbit); This will cause an exception to be thrown if the stream state changes to fail or bad.