CS1371 Introduction to Computing for Engineers - PowerPoint PPT Presentation

1 / 37
About This Presentation
Title:

CS1371 Introduction to Computing for Engineers

Description:

Handling run-time errors is a nasty business. When an error occurs deep in a nested set of function calls, that function may ... This might be a program error; ... – PowerPoint PPT presentation

Number of Views:67
Avg rating:3.0/5.0
Slides: 38
Provided by: david3049
Category:

less

Transcript and Presenter's Notes

Title: CS1371 Introduction to Computing for Engineers


1
CS1371Introduction to Computing for Engineers
  • Exceptions

2
Exception Processing
  • How to Take Advantage of the Exception Mechanism
  • Error handling
  • Exceptions

Learning Objectives Understanding Java Exceptions
3
Background
  • Handling run-time errors is a nasty business
  • When an error occurs deep in a nested set of
    function calls, that function may not have enough
    info to decide how to deal with it.
  • Example
  • The File I/O routine tries to read from a file
    and sees end-of-file. What should it do?
  • This might be a program error
  • However, it might also be a normal occurrence if
    the programmer wanted to read the whole file
  • Passing the result back through extra parameters
    in the function calls is a terrible way to solve
    this problem
  • Java uses the Exception mechanism

4
Old Stuff an ancient calculator machine
5
(No Transcript)
6
From the manual
  • To perform division one must first press a small
    button on the carriage which indicates where the
    decimal point should be situated in the quotient.
    Then, the dividend is entered on the big
    keyboard, and the "ENTER DIVD" button is pressed.
    This shifts the carriage over to the position
    indicated for the decimal point, and enters the
    dividend into the accumulator. Then, the keyboard
    is cleared (if the "ADD" key is on, the keyboard
    clears automatically, however, if it is off, the
    keyboard must be cleared manually with the "K B
    CLEAR" key), and the divisor entered into the big
    keyboard. Then, BOTH divide keys are depressed
    simultaneously, and the machine begins a process
    of shifting the carriage to the right to find a
    point where the divisor can start to be
    subtracted from the dividend. Once that point is
    found, then successive subtractions of the
    divisor occur until an overdraft (IE the
    accumulator goes negative) occurs, and each
    subtraction is counted in the counter register. A
    single addition of the divisor corrects for the
    overdraft, and then the carriage shifts to the
    left, and the process repeats until the quotient
    is left in the counter register, and the
    remainder is left in the accumulator.

7
142245/435 ?
8
Slight problem
  • If division by zero is attempted the calculator
    just keeps trying to subtract and never stops.
    Very exciting!
  • Okay for a machine with an operator but what
    about an automatic machine?
  • Need to take action upon encountering certain
    error conditions like "division by zero"
  • Architecture modified to detect error conditions
    and branch to handler code.
  • So how do we handle the situation?

9
Early Approaches to Errors
  • Fortran
  • READ(5,1,END10,ERR20) A,B,C
  • Basic
  • ONERROR GOTO 100
  • C
  • ch getchar()
  • / ch will be set equal to EOF on end of file /

10
Basic Problems
  • Programmers never think they will make errors
  • Programmers are wrong a lot!
  • Want to make code robust
  • Want to force users to maintain robustness
  • Need a "clean" way of handling problems

11
Solutions?
  • Could have methods return a value that tells us
    whether or not we had an error?
  • Then cant return anything else or
  • Have to return a composite object
  • Even with some kind of error code
  • Does it give us enough information?
  • Does it give us flexibility
  • Does it include a way to make sure we check it?

12
Outdated way of handling things 1
  • if (someMethod( ) true)
  • if (someOtherMethod( ) true)
  • if (someThirdMethod( ) true)
  • // no errors do intended actions
  • else
  • // handle error caused by someThirdMethod( )
  • else
  • // handle some error caused by someOtherMethod(
    )
  • else
  • // handle some error caused by someMethod( )

13
How about Global Variables?
  • Another way to deal with error handling is to
    have the value of a global variable represent the
    error.
  • int iErrorValue 0
  • public void someMethod( )
  • // do someMethods stuff here
  • // if there is an error, then set iErrorValue
    1
  • public void someOtherMethod( )
  • // do someOtherMethods stuff here
  • // if there is an error, then set iErrorValue
    2
  • public void someThirdMethod( )
  • // do someThirdMethods stuff here
  • // if there is an error, then set iErrorValue
    3

14
How about Global Variables?
  • But What if the run-time error stopped us from
    continuing?
  • For example What if someMethod( ) failed in such
    a way that we cannot go on to someOtherMethod( )?
  • To cope, we find ourselves with code thats
    nearly as messy as the earlier example which
    featured multiple nested-ifs
  • public void doIt()
  • someMethod()
  • someOtherMethod()
  • someLastMethod()
  • if (iErrorValue 1)
  • ...
  • if (iErrorValue 2)
  • ...
  • if (iErrorValue 3)
  • ...

15
How about Global Variables?
  • public void doit( )
  • someMethod( )
  • if (iErrorValue 1)
  • / Handle Error 1 here /
  • else
  • someOtherMethod( )
  • if (iErrorValue 2)
  • / handle Error 2 here /
  • else
  • someThirdMethod( )
  • if (iErrorValue 3)
  • / Handle Error 3 here /
  • else
  • / do intended actions here /
  • // else
  • // else
  • // else
  • // doit

(Do we prefer robustness or clarity/maintainabilit
y?)
Dont write code like this!
16
Java Solution
  • Exceptions
  • Sense "I take exception to that."
  • Exceptions are thrown
  • like an NFL referee throws a penalty flag
  • Exceptions can be thrown by Java
  • Exceptions can be thrown by you!

17
What you need to know
  • What happens when an exception is thrown
  • What are your choices for handling exceptions
  • The different kinds of exceptions
  • Details of the exception classes
  • Why and when you should use exceptions
  • Some typical scenarios

18
Two Main Ideas
Handling Exceptions thrown by someone else
Throwing Exceptions
19
When an exception is thrown
  • An exception object is created (on the heap)
  • The current "context" is halted/aborted
  • Execution starts in some error handling code
  • Can be in current method
  • Can be external to current method
  • The error handling code has access to the
    exception object which can be used to
  • Access a String message contained in the
    exception
  • Determine what type of exception was thrown
  • Print a stack trace
  • Other cool stuff (like rethrow the exception,
    increment a counter, etc.)

20
Choices for handling exceptions
  • Handle in current method
  • try
  • / Code that might throw an exception /
  • catch (ExceptionType )
  • / Code that handles exception /
  • Handle outside current method (make the calling
    method deal with it!) so just use a special
    header for your problematic method
  • void someMethod() throws Exception

More details on this later!
21
The different kinds of exceptions
  • Error
  • For the big guys
  • Exception
  • The "standard" exception
  • Java enforces handling
  • An unusual condition
  • RuntimeException
  • e.g. classCast Exception
  • Can indicate using a class improperly
  • No special handling is required

22
Nitty Gritty
  • A method which throws an exception must
    explicitly
  • "announce" this fact (compiler enforced) in the
    method
  • header throw clause
  • public void someMethod() throws SomeException
  • UNLESS
  • The exception is a RuntimeException (or a child
    of RuntimeException)OR
  • The exception is handled inside the method

23
Heres the idea
  • If you as a developer write a class with a method
    that throws a non-runtime exception then Java
    forces all users of the class to deal with it.
  • This is unlike earlier programming languages
    where there was no way to insure that programmers
    properly handled error conditions.
  • We try to deal with problems at compile time as
    opposed to runtime

24
But what about Runtime Exceptions?
  • Runtime exceptions are the type of exceptions
    that
  • can occur in almost every method and
  • including code for these conditions would be
    burdensome
  • Runtime Exception Examples
  • ArithmeticException
  • ClassCastException
  • EmptyStackException
  • IllegalArgumentException
  • IndexOutOfBoundsException
  • UnsupportedOperationException
  • NegativeArraySizeException
  • NoSuchElementException
  • NullPointerException

So no special note must be made in method
headers.
And it doesnt have to be handled. Program can be
allowed to terminate.
25
Making a method handle its own exceptions
  • One or more statements that might throw an
    exception are placed in a try block
  • The try block is followed by one or more catch
    blocks
  • catch(IOException ioe)
  • / Code to handle IOException here e.g./
  • System.out.println(ioe.getMessage())
  • catch(Exception e)
  • / Code to handle other exceptions here /

26
Finally Blocks
  • In certain cases (no matter what) it is desirable
    to have some code that will be executed after the
    try block. (Like closing a file or a network
    connection).
  • This means whether or not exceptions were
    encountered.
  • The solution is the finally block
  • try
  • catch(Ex1 e)
  • catch(Ex2 e)
  • finally
  • / Code that will execute! /

27
When Catching Exceptions you can . . .
  • Print an error message
  • Log the exception
  • Retry the method(maybe with default parameters)
  • Restore the system to some previouslyknown
    "good" state.
  • Set the system to some "safe" state.
  • Let exception propagate to whoever called the
    method in which the exception arose
  • Catch it and ignore it
  • "Catch it and ignore it" is generally bad If
    the error was serious enough to throw an
    exception, it should be dealt with, not ignored.

OOA/OOD/OOP "Who" knows enough to handle the
exception?
28
What you need to know
  • What happens when an exception is thrown
  • What are your choices for handling exceptions
  • The different kinds of exceptions
  • Now, some more details of the exception classes
  • Why and when you should use exceptions
  • Some typical scenarios

29
Two Main Ideas
Handling Exceptions Thrown by Someone
Throwing Exceptions
30
Scenarios
  • You are writing a collection class and you are
    wondering how to handle the condition where the
    collection is empty but the bone-headed user
    forgot to check.
  • You would like to see a fairly complex yet
    crystal clear example of exception usage
  • Might be you if its late enough!

31
  • You are writing a collection class and you are
    wondering how to handle the condition where the
    collection is empty but the bone-headed user
    forgot to check.
  • // class Queue (continued)
  • public Object dequeue() throws Exception
  • if(isEmpty())
  • throw new Exception("Should check
    isEmpty() "
  • "before dequeueing")
  • else
  • // normal processing
  • // return the front object
  • // ...

Note Were just throwing a plain old Exception
32
How does one use this queue?
  • do
  • try
  • element myQueue.dequeue()
  • catch(Exception whoops)
  • System.out.println("This cant be happening!")
  • System.out.println(whoops.getMessage())
  • while (! myQueue.isEmpty())

33
In which case...
  • // class Queue (continued)
  • public Object dequeue() throws RuntimeException
  • if(isEmpty())
  • throw new RuntimeException
  • ("Should check isEmpty()before
    dequeueing")
  • else
  • // return the front object
  • // ...

34
How do you use this queue?
  • while(! myQueue.isEmpty())
  • element myQueue.dequeue()
  • .
  • .
  • .

If an exception is thrown, the program will
terminate. Notice the compiler doesnt force the
user of the code to do anything special.
35
Be sure to
  • Not overuse exceptions
  • Dont use to indicate normal operations
  • Not underuse exceptions
  • Design by Contract
  • Dont ignore
  • Catch exceptions
  • Throw exceptions (Dont have to!)

36
Questions?
37
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com