Error Handling with Exceptions - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

Error Handling with Exceptions

Description:

Error Handling with Exceptions * * Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established by ... – PowerPoint PPT presentation

Number of Views:167
Avg rating:3.0/5.0
Slides: 34
Provided by: Virtua57
Category:

less

Transcript and Presenter's Notes

Title: Error Handling with Exceptions


1
  • Error Handling with Exceptions

2
Concepts
  • C and other earlier languages often had multiple
    error-handling schemes, and these were generally
    established by convention and not as part of the
    programming language. Typically, you returned a
    special value or set a flag, and the recipient
    was supposed to look at the value or the flag and
    determine that something was amiss.
  • However, as the years passed, it was discovered
    that programmers who use a library tend to think
    of themselves as invincibleas in "Yes, errors
    might happen to others, but not in my code."

3
  • The solution is to take the casual nature out of
    error handling and to enforce formality.
  • The word "exception" is meant in the sense of "I
    take exception to that."
  • The other rather significant benefit of
    exceptions is that they tend to reduce the
    complexity of error-handling code

4
Basic exceptions
  • An exceptional condition is a problem that
    prevents the continuation of the current method
    or scope. Its important to distinguish an
    exceptional condition from a normal problem, in
    which you have enough information in the current
    context to somehow cope with the difficulty.

5
  • When you throw an exception, several things
    happen.
  • First, the exception object is created in the
    same way that any Java object is created on the
    heap, with new.
  • Then the current path of execution (the one you
    couldnt continue) is stopped and the reference
    for the exception object is ejected from the
    current context.
  • At this point the exception-handling mechanism
    takes over and begins to look for an appropriate
    place to continue executing the program. This
    appropriate place is the exception handler, whose
    job is to recover from the problem so the program
    can either try another tack or just continue.

6
Exception arguments
  • As with any object in Java, you always create
    exceptions on the heap using new, which allocates
    storage and calls a constructor.
  • There are two constructors in all standard
    exceptions The first is the default constructor,
    and the second takes a string argument so that
    you can place pertinent information in the
    exception

7
  • The keyword throw produces a number of
    interesting results. After creating an exception
    object with new, you give the resulting reference
    to throw.
  • You can throw any type of Throwable, which is the
    exception root class

8
Catching an exception
  • The concept of a guarded region.
  • The try block
  • Exception handlers

9
Guarded region
  • The guarded region is a section of code that
    might produce exceptions and is followed by the
    code to handle those exceptions.

10
The try block
  • If youre inside a method and you throw an
    exception (or another method that you call within
    this method throws an exception), that method
    will exit in the process of throwing. If you
    dont want a throw to exit the method, you can
    set up a special block within that method to
    capture the exception. This is called the try
    block because you "try" your various method calls
    there.
  • The try block is an ordinary scope preceded by
    the keyword try

11
try block - Syntax
  • With exception handling, you put everything in a
    try block and capture all the exceptions in one
    place. This means your code is much easier to
    write and read because the goal of the code is
    not confused with the error checking.

12
Exception handlers
  • The thrown exception must end up someplace. This
    "place" is the exception handler, and theres one
    for every exception type you want to catch.
    Exception handlers immediately follow the try
    block and are denoted by the keyword catch.

13
Exception handlers Syntax
14
  • Each catch clause (exception handler) is like a
    little method that takes one and only one
    argument of a particular type. The identifier
    (id1, id2, and so on) can be used inside the
    handler, just like a method argument. Sometimes
    you never use the identifier because the type of
    the exception gives you enough information to
    deal with the exception, but the identifier must
    still be there.
  • The handlers must appear directly after the try
    block.

15
Termination vs. resumption
  • There are two basic models in exception-handling
    theory.
  • Java supports termination, in which you assume
    that the error is so critical that theres no way
    to get back to where the exception occurred.
    Whoever threw the exception decided that there
    was no way to salvage the situation, and they
    dont want to come back.

16
  • The alternative is called resumption. It means
    that the exception handler is expected to do
    something to rectify the situation, and then the
    faulting method is retried, presuming success the
    second time. If you want resumption, it means you
    still hope to continue execution after the
    exception is handled.

17
Creating your own exceptions
  • Youre not stuck using the existing Java
    exceptions. The Java exception hierarchy cant
    foresee all the errors you might want to report,
    so you can create your own to denote a special
    problem that your library might encounter.

18
Exceptions and logging
  • You may also want to log the output using the
    java.util.logging facility.
  • The static Logger.getLogger( ) method creates a
    Logger object associated with the String argument
    (usually the name of the package and class that
    the errors are about) which sends its output to
    System.err. The easiest way to write to a Logger
    is just to call the method associated with the
    level of logging message.

19
The exception specification
  • In Java, youre encouraged to inform the client
    programmer, who calls your method, of the
    exceptions that might be thrown from your method.
    This is civilized, because the caller can then
    know exactly what code to write to catch all
    potential exceptions.

20
  • The exception specification uses an additional
    keyword, throws, followed by a list of all the
    potential exception types. So your method
    definition might look like this

21
Catching any exception
  • It is possible to create a handler that catches
    any type of exception. You do this by catching
    the base-class exception type Exception (there
    are other types of base exceptions, but Exception
    is the base thats pertinent to virtually all
    programming activities)

22
The stack trace
  • The information provided by printStackTrace( )
    can also be accessed directly using
    getStackTrace( ). This method returns an array of
    stack trace elements, each representing one stack
    frame. Element zero is the top of the stack, and
    is the last method invocation in the sequence
    (the point this Throwable was created and
    thrown). The last element of the array and the
    bottom of the stack is the first method
    invocation in the sequence.

23
Rethrowing an exception
  • Sometimes youll want to rethrow the exception
    that you just caught, particularly when you use
    Exception to catch any exception.
  • Since you already have the reference to the
    current exception, you can simply rethrow that
    reference

24
  • Rethrowing an exception causes it to go to the
    exception handlers in the nexthigher context.
  • Any further catch clauses for the same try block
    are still ignored. In addition, everything about
    the exception object is preserved, so the handler
    at the higher context that catches the specific
    exception type can extract all the information
    from that object.

25
Exception chaining
  • Often you want to catch one exception and throw
    another, but still keep the information about the
    originating exceptionthis is called exception
    chaining.
  • Prior to JDK 1.4, programmers had to write their
    own code to preserve the original exception
    information, but now all Throwable subclasses
    have the option to take a cause object in their
    constructor.

26
Standard Java exceptions
  • The Java class Throwable describes anything that
    can be thrown as an exception. There are two
    general types of Throwable objects ("types of
    "inherited from").
  • Error represents compile-time and system errors
    that you dont worry about catching (except in
    very special cases).
  • Exception is the basic type that can be thrown
    from any of the standard Java library class
    methods and from your methods and runtime
    accidents. So the Java programmers base type of
    interest is usually Exception.

27
Performing cleanup with finally
  • Theres often some piece of code that you want to
    execute whether or not an exception is thrown
    within a try block. This usually pertains to some
    operation other than memory recovery (since
    thats taken care of by the garbage collector).
    To achieve this effect, you use a finally clause4
    at the end of all the exception handlers.

28
Syntax
29
Whats finally for?
  • The finally clause is necessary when you need to
    set something other than memory back to its
    original state.

30
Using finally during return
  • Because a finally clause is always executed, its
    possible to return from multiple points within a
    method and still guarantee that important cleanup
    will be performed.

31
Exception restrictions
  • When you override a method, you can throw only
    the exceptions that have been specified in the
    base-class version of the method.

32
Exception matching
  • When an exception is thrown, the
    exception-handling system looks through the
    "nearest handlers in the order they are written.
    When it finds a match, the exception is
    considered handled, and no further searching
    occurs.
  • Matching an exception doesnt require a perfect
    match between the exception and its handler. A
    derived-class object will match a handler for the
    base class.

33
Summary
  • Exceptions are integral to programming with Java
    you can accomplish only so much without knowing
    how to work with them. For that reason,
    exceptions are introduced at this point in the
    bookthere are many libraries (like I/O,
    mentioned earlier) that you cant use without
    handling exceptions.
Write a Comment
User Comments (0)
About PowerShow.com