Exceptions - PowerPoint PPT Presentation

1 / 24
About This Presentation
Title:

Exceptions

Description:

Por lo general en las clases de programaci n no prestamos mucha atenci n al rea ... o de una librer a) provee un mecaismo que indica que algo extra o ha ocurrido. ... – PowerPoint PPT presentation

Number of Views:34
Avg rating:3.0/5.0
Slides: 25
Provided by: anacgonz
Category:
Tags: algo | exceptions

less

Transcript and Presenter's Notes

Title: Exceptions


1
Exceptions
  • Capítulo 2

2
Introducción
  • Por lo general en las clases de programación no
    prestamos mucha atención al área de detectar y
    manejar errores de corrida.

3
Introducción
  • Still, in the real world, we must write code to
    handle these situations or exceptional cases ,
  • Invalid array indices
  • Check for NULL pointers returned from calls to
    new
  • Check for NULL pointers returned from file open
    calls
  • Check function parameters validity
  • Check user input validity

4
C exception-handling facilities(idea general)
  • Un código (nuestro o de una librería) provee un
    mecaismo que indica que algo extraño ha ocurrido.
  • Esto se conoce como throwing an exception
  • En otro lugar en el program se coloca el código
    que maneja el caso excepcional
  • Esto se conoce como handling the exception

5
(No Transcript)
6
(No Transcript)
7
Toy Example
  • Imagine people rarely run out of milkcout ltlt
    Enter number of donutscin gtgt donutscout ltlt
    Enter number of glasses of milkcin gtgt
    milkdpg donuts/static_castltdoublegt(milk)cout
    ltlt donuts ltlt donuts.\n ltlt milk ltlt glasses
    of milk.\n ltlt You have ltlt dpg ltlt
    donuts for each glass of milk.\n
  • Basic code assumes never run out of milk

8
  • Notice If no milk?divide by zero error!
  • Program should accommodate unlikelysituation of
    running out of milk
  • Can use simple if-else structureif (milk lt
    0) cout ltlt Go buy some milk!\nelse
  • Notice no exception-handling here

9
(No Transcript)
10
Toy Example try-catch
  • Try block
  • Handles normal situation
  • Catch block
  • Handles exceptional situations
  • Provides separation of normal fromexceptional
  • Not big deal for this simple example,
    butimportant concept

11
try block
  • Basic method of exception-handling
    istry-throw-catch
  • Try blocktry Some_Code
  • Contains code for basic algorithm when allgoes
    smoothly

12
catch-block
  • When something thrown ? goessomewhere
  • In C, flow of control goes from try-block
    tocatch-block
  • try-block is exited and control passes to
    catch-block
  • Executing catch block called catching
    theexception
  • Exceptions must be handled in somecatch block

13
catch-block More
  • Recallcatch(int e) cout ltlt e ltlt donuts,
    and no milk!\n ltlt Go buy some milk.\n
  • Looks like function definition with
    intparameter!
  • Not a function, but works similarly
  • Throw like function call

14
catch-block Parameter
  • Recall catch(int e)
  • e called catch-block parameter
  • Each catch block can have at most ONEcatch-block
    parameter
  • Does two things
  • 1- type name specifies what kind of thrownvalue
    the catch-block can catch
  • 2- Provides name for thrown value caughtcan do
    things with value

15
Defining Exception Classes
  • throw statement can throw value of anytype
  • Exception class
  • Contains objects with information to bethrown
  • Can have different types identifying each
    possible exceptional situation
  • Still just a class
  • An exception class due to how its used

16
Exception Class for Toy Example
  • Considerclass NoMilkpublic NoMilk()
    NoMilk(int howMany) count(howMany) int
    getcount() const return count private int
    count
  • throw NoMilk(donuts)
  • Invokes constructor of NoMilk class

17
Multiple Throws and Catches
  • try-block typically throws any number
    ofexception values, of differing types
  • 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
    eachtry-block
  • To catch all-possible exceptions to be thrown

18
Catching
  • Order of catch blocks important
  • Catch-blocks tried in order after try-block
  • First match handles it!
  • Considercatch ()
  • Called catch-all, default exception handler
  • Catches any exception
  • Ensure catch-all placed AFTER more
    specificexceptions!
  • Or others will never be caught!

19
Trivial Exception Classes
  • Considerclass DivideByZero
  • No member variables
  • No member functions (except defaultconstructor)
  • Nothing but its name, which is enough
  • Might be nothing to do with exception value
  • Used simply to get to catch block
  • Can omit catch block parameter

20
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 incalling
    functions try-catch-block
  • Place call inside try-block
  • Handle in catch-block after try-block

21
Throwing Exception in Function Example
  • Considertry quotient safeDivide(num,
    den)catch (DivideByZero)
  • safeDivide() function throws DividebyZeroexceptio
    n
  • Handled back in callers catch-block

22
Exception Specification
  • Functions that dont catch exceptions
  • Should warn users that it could throw
  • But it wont catch!
  • Should list such exceptionsdouble
    safeDivide(int top, int bottom) throw
    (DividebyZero)
  • Called exception specification or throw list
  • Should be in declaration and definition
  • All types listed handled normally
  • If no throw list ? all types considered there

23
Throw List
  • If exception thrown in function NOT inthrow
    list
  • No errors (compile or run-time)
  • Function unexpected() automatically called
  • Default behavior is to terminate
  • Can modify behavior
  • Same result if no catch-block found

24
Throw List Summary
  • void someFunction() throw(DividebyZero,
    OtherException)//Exception types DividebyZero
    or OtherException//treated normally. All others
    invoke unexpected()
  • void someFunction() throw ()//Empty exception
    list, all exceptions invokeunexpected()
  • void someFunction()//All exceptions of all
    types treated normally
Write a Comment
User Comments (0)
About PowerShow.com