Lecture: Exceptions

Embed Size (px)

Citation preview

  • 8/22/2019 Lecture: Exceptions

    1/30

    Object Oriented Programming

    Using C++

    Exceptions

  • 8/22/2019 Lecture: Exceptions

    2/30

    Introduction

    Errors can be dealt with at place error occurs

    Easy to see if proper error checking implemented Harder to read application itself and see how code works

    Exception handling

    Makes clear, robust, fault-tolerant programs C++ removes error handling code from "main line" of

    program

    Common failures

    new not allocating memory Out of bounds array subscript

    Division by zero

    Invalid function parameters

  • 8/22/2019 Lecture: Exceptions

    3/30

    Introduction (II)

    Exception handling - catch errors before theyoccur

    Deals with synchronous errors (i.E., Divide by zero)

    Does not deal with asynchronous errors - disk I/Ocompletions, mouse clicks - use interrupt processing

    Used when system can recover from error

    Exception handler - recovery procedure

    Useful when program cannot recover but must shutdown cleanly

  • 8/22/2019 Lecture: Exceptions

    4/30

    Error Handling Error ConditionsAn error condition(or just error) is a condition, occurring during runtime, that

    cannot be handled by the normal flow of execution.An error condition is not the same as a bug in the code.

    So we are not referring to compilation errors.

    But someerror conditions are caused by bugs.

    However, in our discussion of error handling, we will usually assume that our code

    is properly written.An error condition does not mean that the user did something wrong.

    Although someerror conditions are caused by user mistakes.

    Example

    Suppose we have a function copyFile, which opens a file, reads its contents into

    a buffer, and writes them to another file. Function copyFile is called in order to read a file on a device that is accessed via

    a network.

    Halfway through reading the file, the network goes down.

    The function is supposed to read the file. This is now impossible. The normal flow

    of execution cannot handle this. We have an error condition.

  • 8/22/2019 Lecture: Exceptions

    5/30

    Basics of C++ Exception Handling: try,

    throw, catch

    A function can throw an exception object if it detects

    an error

    Object typically a character string (error message) orclass object

    If exception handler exists, exception caught andhandled

    Otherwise, program terminates

  • 8/22/2019 Lecture: Exceptions

    6/30

    Basics of C++ Exception Handling: try,

    throw, catch (II)

    Format

    Enclose code that may have an error in tryblock

    Follow with one or more catch blocks

    Each catch block has an exception handler Ifexception occurs and matches parameter incatch block, code in catch block executed

    If no exception thrown, exception handlers skipped

    and control resumes after catch blocks throw point - place where exception occurred

    Control cannot return to throw point

  • 8/22/2019 Lecture: Exceptions

    7/30

    The three purposes of an exception handler:

    1. Recover from an exception to safely continueexecution

    2. If full recovery is not possible, display or log errormessage(s)

    3. If the exception cannot be handled locally, clean

    up local resources and re-raise the exception topropagate it to another handler

  • 8/22/2019 Lecture: Exceptions

    8/30

    Exception-Handling Overview

    C++ codetry {code that may raise exception

    }

    catch (exceptionType){

    code to handle exception

    }

    try block encloses code that may raise exception

    One or more catch blocks follow Catch and handle exception, if appropriate

    Take parameter; if named, can access exception object

  • 8/22/2019 Lecture: Exceptions

    9/30

    Exception-Handling Overview

    Throw point Location in try block where exception occurred

    If exception handled

    Program skips remainder oftry block Resumes after catch blocks

    If not handled

    Function terminates

    Looks for enclosingcatch block

    If no exception

    Program skips catch blocks

  • 8/22/2019 Lecture: Exceptions

    10/30

    Simple Exception Handler -- Example

    main()

    {//try Block

    try {

    throw(long(1));//catch(long) call

    }

    //Handlerscatch (int x)

    {cout

  • 8/22/2019 Lecture: Exceptions

    11/30

    Example 1int main

    { for(int i=0; i< 5; i++){

    try{if( i< 2)

    throw i;

    cout

  • 8/22/2019 Lecture: Exceptions

    12/30

    Example 2

    classDivideByZeroException{

    Private:

    const char * message;

    Public:DivideByZeroException() : message( "attempted to divide by zero" )

    {

    }

    const char * what() const

    {return message;

    }

    };

  • 8/22/2019 Lecture: Exceptions

    13/30

    Example 2

    double quotient( int numerator, int denominator )

    {

    // throw DivideByZeroException if trying to divide by zero

    if ( denominator == 0 )

    throw DivideByZeroException();

    // return division result

    return (numerator/ denominator);

    }

  • 8/22/2019 Lecture: Exceptions

    14/30

    Example 2int main()

    { int number1, number2;

    double result;cout > number1 >> number2 ) {

    try {

    result = quotient( number1, number2 );

    cout

  • 8/22/2019 Lecture: Exceptions

    15/30

    Example cont.

    Enter two integers (end-of-file to end): 100 7

    The quotient is: 14.2857

    Enter two integers (end-of-file to end): 100 0Exception occurred: attempted to divide by zero

    Enter two integers (end-of-file to end): 33 9

    The quotient is: 3.66667

    Enter two integers (end-of-file to end):

  • 8/22/2019 Lecture: Exceptions

    16/30

    An Exception Handler ClassExample3class zero{

    public:

    zero() //Constructor

    {cout

  • 8/22/2019 Lecture: Exceptions

    17/30

    Example-4

    classDivideByZeroException{

    Private:

    const char * message;

    Public:DivideByZeroException() : message( "attempted to divide by zero" )

    {

    }

    const char * what() const

    { return message;

    }};

  • 8/22/2019 Lecture: Exceptions

    18/30

    Example-4 cont.

    if ( denominator == 0 )

    throw DivideByZeroException();

    catch (DivideByZeroException ex ){

    // exception handler

    cout

  • 8/22/2019 Lecture: Exceptions

    19/30

    Simple Exception-Handling Example: Divide by

    Zero

    Keyword throw

    Throws an exception

    Use when error occurs

    Can throw almost anything (exception object,

    integer, etc.) throw myObject;

    throw 5;

    Exception objects Constructor can take a string (to describe exception)

    Member functionwhat() returns that string

  • 8/22/2019 Lecture: Exceptions

    20/30

    Throwing an Exception

    Exception not required to terminate program

    However, terminates block where exceptionoccurred

  • 8/22/2019 Lecture: Exceptions

    21/30

    Catching an Exception

    Exception handlers are in catch blocks Format: catch( exceptionTypeparameterName){

    exception handling code

    }

    Caught if argument type matches throwtype If not caught then terminate called which (by default) callsabort

  • 8/22/2019 Lecture: Exceptions

    22/30

    Nested try Blocks

    try{

    try{

    ---------

    }

    catch( exceptionType ex)

    {-------------------

    }

    }

    catch( eceptionType ex)

    {

    ------------------------

    }

    This handler catches the

    exception in the inner tryblock

    This handler catches theexception thrown anywherein the outer try block as wellas uncaught exceptions fromthe inner try block

  • 8/22/2019 Lecture: Exceptions

    23/30

    Exampleint main()

    { for(int i=0; i< 3; i++){

    try{ if( i== 0) throw i;

    try{

    if (i== 1) throw i;

    if (i== 2) throw static_cast(i);

    }catch(int i)

    { cout

  • 8/22/2019 Lecture: Exceptions

    24/30

    Matching catch handler for

    inherited classes The type of the parameter is a direct or indirect

    base class of the exception class type, or areference to a direct or indirect base class of the

    exception class, ignoring const.

    Derived class type must appear first and the

    most base class type last.

  • 8/22/2019 Lecture: Exceptions

    25/30

    Exampleclass trouble

    {

    Private:

    const char* pMsg;

    Public:

    trouble (const char* pstr=there is a problem):pMsg(pstr){}virtual const char* what() const;

    }

    const char* trouble::what() const

    { return pMsg; }

  • 8/22/2019 Lecture: Exceptions

    26/30

    Example

    Class moreTrouble: public Trouble

    { public:

    moreTrouble(const char* pstr=there is more trouble):trouble(pstr){ };

    }

    Class bigTrouble: public moreTrouble

    { public:

    bigTrouble(const char* pstr=Really big trouble):moreTrouble( pstr){ };

    }

    E l

  • 8/22/2019 Lecture: Exceptions

    27/30

    Exampleint main()

    { Trouble tb;

    moreTrouble mt;

    big Trouble b;for (int i=0; i

  • 8/22/2019 Lecture: Exceptions

    28/30

    int main()

    { Trouble tb;moreTrouble mt;

    big Trouble b;

    for (int i=0; i

  • 8/22/2019 Lecture: Exceptions

    29/30

    Catching an Exception

    catch parameter matches thrown object when

    They are of the same type

    The catch parameter is apublic base class of the thrown

    object

    The catch parameter is a base-class pointer/ reference type

    and the thrown object is a derived-class pointer/ referencetype

  • 8/22/2019 Lecture: Exceptions

    30/30

    Catching an Exception (II)

    Catch all exceptionscatch(...) - catches all exceptions

    You do not know what type of exception occurred

    There is no parameter name - cannot reference the object

    If no handler matches thrown object

    Searches next enclosingtry block

    If none found, terminate called

    If found, control resumes after lastcatch

    block If several handlers match thrown object, first one found is

    executed