CS 162 Spring 2004 - PowerPoint PPT Presentation

1 / 28
About This Presentation
Title:

CS 162 Spring 2004

Description:

Checked and Unchecked Exceptions. Some exceptions (checked exceptions) MUST be caught. ... Some exceptions (unchecked exceptions) need not be caught. ... – PowerPoint PPT presentation

Number of Views:45
Avg rating:3.0/5.0
Slides: 29
Provided by: timoth90
Category:
Tags: spring | unchecked

less

Transcript and Presenter's Notes

Title: CS 162 Spring 2004


1
CS 162 Spring 2004
  • Chapter 14
  • Exception Handling

2
Stuff happens
  • Programmers have always had to deal with
    exceptional conditions
  • Files cannot be opened
  • Values have wrong format (eg, not numers)
  • Hardware failures
  • Countless others

3
Traditional Techniques
  • Ignore the error, let program crash and burn
  • Print a message and halt
  • Print a message and continue
  • Have a function return a special value
  • Have an error handler function
  • Exceptions and try/catch blocks

4
Returning error flag
  • A common technique is to return a special value
    (0, -1, null string) on error
  • What happens if the caller doesn't check?
  • (this example from C)
  • FILE fp fopen("foo.dat", "r")
  • Int c fgetc(fp) // what happens if open fails?

5
A General Problem with Errors
  • The location where an error is detected
  • Often does not have any idea
  • How the error should be corrected

6
Example - Containers
  • A simple example. We will soon examine a number
    of different types of container
  • What should happen if an attempt is made to
    remove an element from an empty container?
  • The container knows there is a problem, but has
    no idea what this means in application.

7
Detection and Recovery
  • We say there is a difference between error
    detection and error recovery
  • Generally the two are handled in different parts
    of an application.
  • Need to ensure that when an error is detected,
    that there is some recovery strategy.

8
Java Solution, Throw and Try/Catch
  • The solution in Java is to split error handling
    into two statements
  • Throw to indicate an exception has been detected
  • Try/catch to handle the exceptional situation.

9
Throw statement
  • When an error is detected, you throw an object.
  • Generally a special object built just for this
    purpose.
  • Object can have constructor, can carry whatever
    information you want.
  • There are library classes for exceptions.

10
Throw example
  • Public class BankAccount
  • public void withdraw(double amount)
  • if (amount gt balance)
  • IllegalArgumentException excep
  • new IllegalArgumentException
  • ("amount exceeds
    balance")
  • throw excep

11
Thrown object needs no name
  • Public class BankAccount
  • public void withdraw(double amount)
  • if (amount gt balance)
  • throw new IllegalArgumentException
  • ("amount exceeds
    balance")

12
What happens next?
  • When exception is thrown, control is transferred.
  • Looks for surrounding exception handler
  • If none is found (which is usual case) method
    returns and looks for handler in caller.
  • Can exit that method, etc, til handler found.

13
Exception handlers
  • Handers use try/catch syntax
  • try
  • // whatever
  • foo()
  • catch (IllegalArgumentException e)
  • // do recovery

14
Exceptions and Handlers
  • Exceptions are where the error is detected.
  • Handlers are where the error is corrected, often
    in a surrounding method, has more application
    knowledge, knows what the exception means (I.e.,
    what trying to remove a value from an empty
    container means).

15
Standard Exceptions
  • Java provides exception hierarchy
  • Exception
  • IOException
  • EOFException, FileNotFoundException,
  • MalformedURLException, UnknownHostException
  • RuntimeException
  • ArithmeticException, ClassCastException
  • IllegalArgumentException, NullPointerException
  • IllegalStateException, NoSuchElementException
  • indexOutOfBoundsException
  • ArrayIndexOutOfBoundsException

16
Checked and Unchecked Exceptions
  • Some exceptions (checked exceptions) MUST be
    caught. Examples, IOExceptions, most user defined
    exceptions
  • Some exceptions (unchecked exceptions) need not
    be caught. Examples, Numeric overflow, null
    pointer error, array bounds errors. Will halt
    program if not caught.

17
Using Inheritance
  • Often New Classes formed using Inheritance
  • Class myAppException extends IllegalArgumentExcept
    ion
  • public MyAppException(String why)
  • super(why)

18
Method documentation
  • A method that can throw an exception must
    document the fact
  • Public void read(BufferedReader in) throws
    IOException
  • value Double.parseDouble(in.readLine())
  • // readLine can throw exception

19
Passing on an exception
  • If a method doesn't handle an exception, it must
    pass it along
  • Public void handleInput(BufferedReader in) throws
    IOException
  • read(in) // can throw exception

20
Why not handle it?
  • It is best not to handle an exception if you
    don't know how to fix it. (That is, if you can't
    do recovery).
  • Pass it along to somebody who DOES know what it
    means and how to fix it.

21
Writing a Handler
  • A handler can have whatever statements are needed
    to handle exception. Often just report and quit.
  • Try
  • catch (IOException e)
  • System.out.println("caught I/O Exception "
    e)
  • System.exit(1)

22
After Exception Handled
  • After the exception is handled, execution
    continues with statement AFTER the try block.
  • Does NOT go back to throw statement. In general
    can not get back to point where statement thrown.

23
The Exception Value
  • The exception value is like an argument. It is
    whatever was thrown. Should at least know how to
    print itself (method tostring()).
  • Try
  • catch (IOException e)
  • System.out.println("caught I/O Except" e)

24
Printing Stack Trace
  • A common task is to print stack trace (helps
    debugging). A method in class Exception
  • Try
  • catch (IOException e)
  • System.out.println("got error " e)
  • e.printStackTrace()

25
Using Polymorphism
  • A catch clause will catch subclasses as well.
  • Try
  • catch (IndexOutOfBoundsException e)
  • // will handle
  • // ArrayIndexOutOfBoundsException

26
A Catch can handle many ecpts
  • Try
  • .
  • catch (IOException e)
  • catch (NullPointerException f)

27
Exceptions passing through
  • If the particular exception thrown is not on
    list, will keep looking up the call chain.

28
Finally
  • A special catch clause named finally can be used
    for code that should always be executed
  • Try
  • catch(Exception e)
  • finally
  • // whatever should always be done
Write a Comment
User Comments (0)
About PowerShow.com