Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.

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

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
 2006 Pearson Education, Inc. All rights reserved. Exception Handling in C++ CS-2303, C-Term Exception Handling in C++ CS-2303 System Programming.
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.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Exception Handling: A Deeper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
C++ Exception Handling
1 CSC241: Object Oriented Programming Lecture No 28.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
Exceptions David Rabinowitz. March 3rd, 2004 Object Oriented Design Course 2 The Role of Exceptions Definition: a method succeeds if it terminates in.
© 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.
Advanced Java Course Exception Handling. Throwables Class Throwable has two subclasses: –Error So bad that you never even think about trying to catch.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
1 Exceptions and error handling. 2 Java exception mechanism when an error or exceptional condition occurs, you throw an exception which is caught by an.
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.
Chapter 12: Exception Handling
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.
Introduction to Exception Handling and Defensive Programming.
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 Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Exceptions cs1043. Program Exceptions When a program detects an error, what should it do? – Nothing, simply allow the program to fail. – Implement a course.
COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
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.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
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 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.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Eighth Lecture Exception Handling in Java
Exception handling.
Exception Handling in C++
Exceptions Error Handling and Recovery
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
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Why exception handling in C++?
Chapter 14: Exception Handling
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component errors Class might perform incorrectly invalid array index Pop() empty stack

Handling errors Most errors are unpleasant to handle The programmer should not just abort the program with an assertion failure; the user may lose all work performed during the program session Instead, the program must do the best it can to recover, and exit gracefully, only if it is really necessary.

Reaction to error Conditions Returning an error code #define FILE_OPEN_ERROR 1 #define OK 0 int openMyFile() { FILE * f = fopen(“File.txt”, “r”); if ( f == NULL ) return FILE_OPEN_ERROR; else /* Do things to a file*/ … return OK; } Advantage: simple to implement Disadvantage: Code contains a lot of error checking

Do nothing Ignore error condition Hard to debug Common approach Simpler to code Hard to debug Program might terminate or abort or produce incorrect answer Location of original problem might be hard to find Can use assert() in the debug mode Can be misleading to the caller. void Stack::push() will not push element when stack is full, however, the caller will think he successfully pushed element on the stack When coping fails, can not simply ignore the problem

Setting an Error Variable You keep a global variable, such as errno Whenever function returns, you can check errno variable if there was an error when executing the function Simple to implement Code still contains a lot of error handling code, ie: if ( errno == ERROR_NO_5 ) { printMessage(ERROR_NO_5);} The error report contains only the type of error, not the name of the offending function Two errors in rapid succession will result in the first one being overwritten Also a problem with multithreaded functions using the same variable

Printing an Error Message Reasonable in debugging mode only Simple Impacts reusability Defeats the purpose of programmatic handling of error conditions No control of program flow After error is printed, the program continues Does not always make sense to the user Example: “System error 0xff4ff45”

Aborting the Program Good for fatal error Good for debugging purposes Undesirable loss of all volatile data accumulated throughout program’s life time

Jumping to an error handler Non-local jump C setjmp() and longjmp() Provides centralized error handler Do not have to worry about stack unwinding Good approach for C programs, BAD for C++ programs When longjmp() leaves stack of the function, no destructors are called for the objects allocated on the stack.

Raising a Signal Explicitly creates Software Interrupt by calling function raise() and specifying interrupt handler Good for hardware interface Memory fault Segmentation violation Bad for typical error handling, signals should only be used for their intended purpose

Raising an Exception C++ has a convenient and safe mechanism to raise exceptions when errors are detected and to transfer both control and error information to code that is competent to deal with the situation Handles stack unwinding Calls destructors Enables a block of code to be protected Cut down on error handling code

Exceptions Exceptions are the proper way to bail out of a situation which cannot be handled easily by a function itself, but which are not disastrous enough for the program to terminate completely. Exceptions provide a flexible layer of flow control between the short-range return and the crude exit()

C++ exceptions When an error is encountered that cannot be handled at the point of detection, an exception can be raised with the command: throw e; Where ‘e’ could be an object, structure, or simple data type. Simple data types are not useful: throw 1; throw “Stack underflow”

C++ Exceptions The try block surrounds statements in which exceptions may be generated Example: try { // Statements in which exceptions // may be thrown } The throw statement should be executed somewhere within the try-block: either directly or from within a function called directly or indirectly from the try-block

Catch The “catch” keyword immediately follows the try-block Catch-block receives the thrown exceptions. Example try { read(); } catch( StackError s) { // Report syntax error in the input file, and close file }

Throwing exceptions in C++ Local objects should not be thrown, nor should pointers to local objects be thrown However, it is possible to throw pointers or references to dynamically generated objects, taking care that the generated object is properly deleted when the generated exception is caught Example: try{ throw new Exception(); } catch( Exception * e) { // process e delete e; // deallocate dynamically created object

Throwing references We could thrown references try { throw *new Exception(); } catch( Exception & e) { // Process e delete &e;

Catching references / Safe This is totally safe try { throw Exception(); } catch(Exception & e) { // } Output: Exception() constructor is called catch block is processed ~Exception() is called when reach end of catch-block

Catching exceptions / Unsafe This is not always safe depending on the nature of Exception destructor try { Exception e; throw e; } catch(Exception & e) { // } Output: Exception() constructor is called ~Exception() destructor is called catch block is processed ~Exception() is destructor is called the second time - Potential problem of double deallocation

Handling multiple exceptions A try block can throw different types of exceptions try { /* code */ } catch( StackError & s ) { // Process StackError } catch(MathError & m ) { // Process MathError ) }

rethrow Occasionally, we want to catch any exceptions that fly past a certain point, just to take some cleanup or protective actions try { /* … */ } catch( … ) { /* evasive action */ throw; } The throw command without an argument in-side a catch clause throws the current error again Errors that current function does not know how to handle must be re-threw

Declaration of exception throwers The declaration of a function that may throw one or more exceptions: void exceptionThrow() throw(char *, int); This function may throw char * and int exceptions Note, declaration of exceptions is not mandatory However, it declared, it notifies the user of a function that this function may throw certain exceptions, which need to be handled Without a function throw list all responsibilities of providing the correct handlers is in the hands of the designer of the program

Derived exceptions Lets assume class D derives from class B and exception of type D is thrown, then we can catch exception D using catch(B) { /* Catch exception B and any classes deriving from it */ } Note: Catch block can only specify the type

Stack unwinding The process of searching “up though the stack” to find a handler for an exception is commonly called “stack unwinding” All objects on the stack between the throw and catch point are properly destroyed by invoking their destructors This activity is of crucial importance, it is guaranteed that all destructors of abandoned stack objects are invoked thus preventing memory leak

Stack unwinding Top of the stack throw Exception e() d() c() Stack unwinds starting from function e(), d(), and c(). Destructors are called in e(), d(), and c() as stack unwinds, until exception is caught at b() Catch Exception b() a() main()

Destructors and uncaught exceptions Uncaught exceptions cause program Abort and exit Destructors should not throw exceptions If a destructor that is invoked while an exception is pending itself raises an exception, the program terminates

Exception advices Don’t throw exceptions from libraries Customers will not know that they need to catch an exception When they catch an exception they will not know how to handle it If you have to throw an exception, specify it in the prototype of the function This makes the user of the function aware that he might need to catch an exception Never throw exceptions to return the result of computation.

What exceptions should you throw? Failure of precondition Resource limitation Device failure Subsystem failure

More advice Catch those exceptions that you can handle Catch and rethrow exceptions that you can partially handle If possible, don’t use pointers and handles on the stack but place then inside objects with proper destructors Don’t throw an exception if you can continue