Exception handling.

Slides:



Advertisements
Similar presentations
Topics Introduction Types of Errors Exceptions Exception Handling
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
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.
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.
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.
Chapter 11 Exception Handling. Objectives Introduction to error handling C-style handling of error-generating code C++-style solution—the try/throw/catch.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
C++ Exception Handling
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  due to poor understanding of the problem and solution.
DYNAMIC MEMORY MANAGEMENT. int x; When the source code containing this statement is compiled and linked, an executable file is generated. When the executable.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
CS Advanced C++ Exception Handling Topic #5.
© 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.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
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.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
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 Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
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.
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.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
LECTURE LECTURE 14 Exception Handling Textbook p
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Exception Handling How to handle the runtime errors.
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.
C ++ MULTIPLE CHOICE QUESTION
Exception Handling in C++
C++ Exceptions.
IS 0020 Program Design and Software Tools
Exceptions Error Handling and Recovery
16 Exception Handling.
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
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
EXCEPTION HANDLING IN C++
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Why exception handling in C++?
Part IX Fundamentals of C and C++ Programming Exception Handling
EXCEPTION HANDLING.
CMSC 202 Lesson 21 Exceptions II.
Exceptions C++ Interlude 3
Chapter 14: Exception Handling
Exceptions with Functions
Chapter 17 Templates and Exceptions Part 2
Advanced C++ Exception Handling
Exception Handling.
Exceptions, Templates, and the Standard Template Library (STL)
DYNAMIC MEMORY MANAGEMENT
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
Exceptions for safe programming.
Exception Handling.
ENERGY 211 / CME 211 Lecture 24 November 14, 2008.
Presentation transcript:

Exception handling

When the error condition occurs, we want to prevent the further execution of the function. While the library function can easily detect error conditions, it can not decide upon an appropriate handling strategy. Only we can decide what action should be taken whenever a particular error condition is met by the function being called. While the user of the library function can not detect error conditions, it can decide upon an appropriate error handling strategy. Exception handling allows the library to sense and dispatch error conditions and the client to handle

If divide by zero error occurs, the traditional c-style solutions are – (i) terminate the program - abort(); this solution is too extreme and drastic. This solution does not achieve anything tangible. (ii) check the parameters before function call – the application programmer to prevalidate the data before passing them as parameters to the function call. The library function should not burden the user for checking the invalid conditions. (iii) return a value representing an error – does not burden the application program to prevalidate. But allows the application program to take corrective action if it detects an error. These solutions are either too strict or too linient in nature.

C++ offers the mechanism of exception handling to the problem of handling unexpected situations during run time. It uses try, throw and catch blocks. float hmean(const float a, const float b) { if (a== -b) throw “bad arguments to hmean()”; return 2.0 * a * b / (a + b ) ; } void main() { char choice ‘y’ ; double x, y, z ; while (choice ==‘y) { cout<<“enter a number: ” ; cin>> x ; cout<<“enter another number: ” ; cin>> y; try { z = hmean(x, y) ;}

catch ( char * s) { cout << s << endl ; cout << “enter a new pair of numbers\n”; continue ; } cout<<“harmonic mean of”<< x <<“and”<< y <<“is “<<z <<endl ; cout << “continue ? (y / n)”; cin >>choice; } cout << “end”; } This provides a way to transfer control from the library to the application. It has three components: ‘throw’ keyword is used to throw an exception. It is followed by a value, such as character string or an object, indicating the nature of the exception.

The library function notifies the user program about the error by throwing an exception. ‘catch’ is used to catch an exception. It begins with ‘catch’ followed by inside () a type declaration indication the type of exception that it catches. Then by a brace enclosed block of code indicating the actions to take. It is the point to which the control should jump when an exception is thrown. ‘try’ block encloses the block of code that is likely to throw an exception. It consists of calls to library functions that are designed to throw errors. One or more ‘catch’ follow the ‘try’. It is followed by a brace – enclosed block of code with in which exception will be caught.

try { z= hmean ( x, y ) ;} If any statement in the try block causes an exception, ‘catch’ block after this will handle that. if (a== -b) throw “bad arguments to hmean() ”; The ‘throw’ statement resembles return statement It causes the control to back up through the sequence of current function calls until it finds a ‘try’ block. In this case, it passes control back to main(). Then it looks for a matching exception handler. ‘catch’ identifies the handler and the ‘char*s’ meaning that this handler catches a string type exception. The thrown exception is assigned to s. the code with in brace is executed.

If try executes without exceptions, the catch block is skipped and the first statement after the handler is executed. It is necessary to catch exceptions:- The program terminates immediately if an exception thrown by a called function is not caught. It is illegal to have a try block without a catch block. void abc(int x) { if (x<0) throw “invalid parameter”; } Abnormal termination occurs due to uncaught exception with the default error message. If the library programmer creates functions that throw exceptions, the application programmer is

compelled to place the calls to such exception throwing library functions inside try block and to provide suitable catch handlers. The list of exceptions a function throws is indicated in its prototype that is placed in the header file. void abc (int) throw (char *, int ) ; Unwinding of the stack :- The throw statement unwinds the stack, cleaning up all objects declared with in the try block by calling their destructors. Next, throw calls to the matching catch handler, passing the parameter object. Throw destroys all objects from the point of throw until the try block (reversal flow of control).

class A { int x; public : A(int p) {x=p; cout<<“A”<<x<<endl; } ~A() { cout << “A” << x << endl ; } }; void abc () { A A_abc(2); cout<<“calling def”; def(); } void def () { A A_def(3); cout<<“calling ghi”; ghi(); } void ghi () { A A_ghi(4); throw “exception from ghi()”;} Void main() { try { A A_main(1); cout<<“calling abc()”; abc(); } catch (char * s) { cout <<s << endl ; } } Output: A1\ calling abc()\ A2\calling def() \A3\Calling ghi() \A4 \~A4\ ~A3\ ~A2\~A1\exception from ghi()

Need to throw class objects:- the problem with throwing values of fundamental data types is limited. If two or more statements in try block throw values of same type, then conflicts arise and it becomes difficult to detect the source of errorin the catch block. The advantage of throwing objects of classes is that the library programmer can define any number of classes as exception classes. class hmeanexcep { char cError[30]; public: hmeanexcep (char*s) { strcpy(cError,s); } char* getcError() { return cError; } };

class gmeanexcep { char cError[30]; public: gmeanexcep (char class gmeanexcep { char cError[30]; public: gmeanexcep (char*s) { strcpy(cError,s); } char* getcError() { return cError; } }; main() { double x,y,z1,z2; cin>>x>>y; try { z1=hmean(x,y); z2=gmean(x,y); } catch (hmeanexcep & e) { cout << e.getcError() << endl; cout<<“Enter a fresh pair of numbers”; continue; }

catch (gmeanexcep & e) { cout <<e catch (gmeanexcep & e) { cout <<e.getcError()<<endl; cout<<“Enter a fresh pair of numbers”; continue; } cout <<“harmonic mean=“<<z1<<endl; cout <<“geometric mean=“<<z2<<endl; } } double hmean(double a, double b) { if (a=-b) throw hmeanexcep(“Exception error - a = -b not allowed”); return 2.0* a * b / (a+b); } double gmean(double a, double b) {if (a*b<0) throw gmeanexcep(“a*b<0 not allowed”); return sqrt(a * b); }

If we declare the object of the exception class in the catch handler, then the thrown object gets copied in to it. This object can be accessed and used. A temporary copy of the object to be thrown is created and thrown. Catching uncaught exceptions We can catch all types of exceptions that were raised in a try block but not caught by any of the catch blocks. The syntax of the catch for this is catch (…) { //action for handling an exception } This acts like default case in if-else construct. The limitations of exception handling is that if a resource has been aquired and the statements

to release the resource are after the throw statements, then the acquired resource may remain locked up. In order to overcome this problem, classes whose objects function like pointers should be devised. Such objects will have pointers embedded in them. Memory will be allocated dynamically for these pointers during the lifetime of the objects. This memory can be deallocated through destructors. Thus, when the object itself is destroyed, the memory locked up and referenced by the embedded pointer will also be destroyed.

class A { public: A(){ cout<<“constructor”; } ~A(){ cout << “destructor”; } }; void abc (int p) { A* Aptr = newA[2] ; if (p<0) throw “invalid argument to abc()” ; } void main () { try { abc (-1) ; } catch (char *s ) cout << s << endl ; } } output: constructor constructor invalid argument to abc()