Lesson: Exceptions - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

Lesson: Exceptions

Description:

The list of methods is known as the call stack (see the next ) ... The Call Stack (or Stack Trace) ... system searches the call stack for a method that ... – PowerPoint PPT presentation

Number of Views:87
Avg rating:3.0/5.0
Slides: 27
Provided by: TimothyCL4
Category:

less

Transcript and Presenter's Notes

Title: Lesson: Exceptions


1
Lesson Exceptions
  • What Is an Exception?
  • A mechanism used to handle errors and other
    exceptional conditions.
  • The Catch or Specify Requirement
  • Java requires the programmer to either
  • Catch an exception that occurs in a method.
  • The catching method takes responsibility and
    handles the exception.
  • Specify (declare) that one can occur in a method.
  • The method passes the buck to the next method.
  • How to Throw Exceptions

2
What is an Exception (Exceptional Event)?
  • An exception is an event, which occurs during the
    execution of a program, that disrupts the normal
    flow of the programs instructions.
  • When an error occurs within a method, the method
    creates an object and hands it off to the runtime
    system. The object, called an exception object,
    contains information about the error, including
    its type and the state of the program when the
    error occurred.
  • Creating an exception object and handing it to
    the runtime system is called throwing an
    exception.
  • After a method throws an exception, the runtime
    system attempts to find something to handle it.
    The set of possible somethings to handle the
    exception is the ordered list of methods that had
    been called to get to the method where the error
    occurred. The list of methods is known as the
    call stack (see the next slide).

3
The Call Stack (or Stack Trace)
The sequence of method calls that leads to an
exception is called the call stackor the stack
trace.
main
4
What Happens When an Exception Occurrs?
  • The runtime system searches the call stack for a
    method that contains a block of code that can
    handle the exception. This block of code is
    called an exception handler.
  • The search begins with the method in which the
    error occurred and proceeds through the call
    stack in the reverse order in which the methods
    were called.
  • When an appropriate handler is found, the runtime
    system passes the exception to the handler. An
    exception handler is considered appropriate if
    the type of the exception object thrown legally
    matches the type that can be handled by the
    handler.
  • The exception handler chosen is said to catch the
    exception.
  • If the runtime system exhaustively searches all
    the methods on the call stack without finding an
    appropriate exception handler, as shown in the
    next figure, the runtime system (and,
    consequently, the program) terminates.

5
What Happens When an Exception Occurrs?
Throws an exception
main
6
Scenario 1 exception is caught
Throws an exception. Does not handle the
exception. Forwards the exception.
Method where an exception was detected
Method without an exception handler
The Exception is not caught here. Forwards the
exception
Method with an exception handler
Catches exception. The exceptionis handled here.
main
7
Scenario 2 exception is not caught
Throws an exception.
Method where an exception was detected
The Exception is not caught here.
Method without an exception handler
Handles some other type of exception.
Method with an exception handler
The Exception is not caught here.
main
8
The Catch or Specify Requirement
  • Valid Java code must honor the Catch or Specify
    Requirement.
  • This means that code that might throw certain
    exceptions must contain either
  • A try statement that catches and handles the
    exception.
  • A method that specifies that it can throw the
    exception.
  • Code that fails to honor the Catch or Specify
    Requirement will not compile.
  • Not all exceptions are subject to the Catch or
    Specify Requirement.

9
The Three Kinds of Exceptions1. Checked Exception
  • These are exceptional conditions that a
    well-written application should anticipate and
    recover from.
  • Example suppose a user enters a name for a
    nonexistent file
  • A method that detects the invalid filename will
    throw a
  • java.io.FileNotFoundException
  • A well-written program must catch this exception
    and take corrective action.
  • Methods in the call stack Must honor the Catch or
    Specify Requirement for the Checked Exception.

10
The Three Kinds of Exceptions2. Error
  • These are exceptional conditions that are
    external to the application, and that the
    application usually cannot anticipate or recover
    from.
  • Example a hardware error occurs in the process
    of reading a file.
  • A method that detects the hardware failure will
    throw a
  • java.io.IOError
  • A method could catch this type of error and
    handle it by notifying the user or printing a
    stack trace and exiting.
  • However, in general, for the Error type of
    exception, the program cannot do anything
    reasonable to recover from the exception.
  • Methods in the call stack are not requried to
    honor the Catch or Specify Requirement for the
    Error type of Exception.

11
The Three Kinds of Exceptions3. Runtime Exception
  • These are exceptional conditions that are
    internal to the application, and that the
    application usually cannot anticipate or recover
    from.
  • These usually indicate programming bugs.
  • Examplea logic error causes a null to be passed
    as a filename.
  • A method that detects the null will throw a
    NullPointerException.
  • A method could catch this type of error do
    something. But, it is best to stop the program
    and eliminate the bug that caused the exception
    to occur.
  • However, in general, for the Runtime Exception,
    the program cannot do anything reasonable to
    recover from the exception.
  • Methods in the call stack are not requried to
    honor the Catch or Specify Requirement for the
    Runtime Exception.

12
How do I know if it is a checked exception or an
unchecked exception?
  • Experienced programmers seem to know which
    exceptions are checked
  • The application can reasonably recover from
    checked exceptions.
  • The application cannot reasonably recover from
    unchecked exceptions.
  • However, there are two ways programmers can
    verify their intuition
  • The compiler tells us which exceptions are
    checked
  • The compiler will report an error if we call a
    method that may throw checked exceptions, and we
    dont implement the Catch or Specify
    Requierement.
  • In Javas exception inheritance hierarchy,
    checked exceptions are not a subclass of the
    RuntimeException or Error classes.

13
Throwable Class and Its Subclasses
  • Throwable objects must be instances of any
    subclass of the Throwable class.

14
How To Setup the Catch Mechanism Constructing an
Exception Handler
  • try
  • /Identify the code that that might cause an
    exception to be thrown, and enclose that code in
    a try block. /
  • catch (ExceptionType1 name1)
  • //code that handles exceptions of type
    ExceptionType1.
  • catch (ExceptionType2 name2)
  • //code that handles exceptions of type
    ExceptionType2.
  • finally
  • //cleanup code, e.g., close file handles.

15
How To Setup the Catch Mechanism Constructing an
Exception Handler Example
  • How to determine which exception(s) can be
    thrown, for example
  • try
  • out new PrintWriter(new FileWriter(OutFile.txt
    ))
  • catch . . .
  • FileWriter(String fileName) throws IOException -
    if the named file exists but is a directory
    rather than a regular file, does not exist but
    cannot be created, or cannot be opened for any
    other reason.
  • It is also possible that a FileNotFoundException,
    a subclass of IOException, could be thrown,
    particularly since the argument of FileWriter is
    intended to be the file name of the file to be
    opened for writing.

16
How To Setup the Catch Mechanism Constructing an
Exception Handler Example
  • Consider the following code within a writeList()
    method.

17
How To Setup the Catch Mechanism Constructing an
Exception Handler Example (Cont)
  • try
  • out new PrintWriter( new FileWriter(OutFile.t
    xt))
  • catch (FileNotFoundException e)
  • System.err.println(Caught FileNotFoundExcept
    ion
  • e.getMessage())
  • //Notify the user and prompt to correct the
    filename.
  • catch (IOException e)
  • System.err.println("Caught IOException "
  • e.getMessage())
  • //Analyze the exception message and try to
    recover.
  • finally if (out ! null)
  • System.out.println("Closing PrintWriter")
  • out.close()
  • else
  • System.out.println("PrintWriter not open")

18
Scenario 1 A FileNotFoundException
Occurrs(Continued)
  • The constructor for the FileWriter throws an
    FileNotFoundException.
  • The runtime system immediately stops executing
    the try block
  • method calls being executed are not completed.
  • The runtime system then starts searching at the
    top of the method call stack for an appropriate
    exception handler.
  • The FileWriter constructor is at the top of the
    call stack. However, the FileWriter constructor
    doesn't have an appropriate exception handler.

19
Scenario 1 A FileNotFoundException
Occurrs(Continued)
  • The runtime system then checks the next method in
    the call stack
  • The writeList method has two exception handlers
  • One for FileNotFoundException and one for
    IOException.
  • The runtime system checks writeList's handlers in
    the order in which they appear after the try
    statement.
  • The argument to the first exception handler
    matches the type of exception that was thrown.
  • So the runtime system ends its search for an
    appropriate exception handler.
  • Now that the runtime has found an appropriate
    handler, the code in that catch block is
    executed.

20
Scenario 1 A FileNotFoundException
Occurrs(Continued)
  • After the exception handler executes, the runtime
    system passes control to the finally block.
  • Code in the finally block executes regardless of
    the exception caught above it.
  • In this scenario, the FileWriter was never opened
    and doesnt need to be closed.
  • After the finally block finishes executing, the
    program continues with the first statement after
    the finally block.

21
Scenario 2 An IOException Occurrs
  • In this scenario, everything happens in the same
    order as in Scenario 1, except for the search for
    an handler.
  • The argument to the first exception handler does
    not match the type of exception that was thrown.
  • So the runtime system searches the next handler,
    which handles exceptions of type IOException.
  • The argument to the second exception handler
    matches the type of exception that was thrown.
  • So the runtime system ends its search for an
    appropriate exception handler.
  • Now that the runtime has found an appropriate
    handler, the code in that catch block is
    executed.

22
Scenario 3 Try Block Executes Successfully
  • In this scenario, all the statements within the
    scope of the try block execute successfully and
    throw no exceptions.
  • Execution falls off the end of the try block, and
    the runtime system passes control to the finally
    block.
  • Because everything was successful, the
    PrintWriter is open when control reaches the
    finally block, which closes the PrintWriter.
  • Again, after the finally block finishes
    executing, the program continues with the first
    statement after the finally block.

23
Question?
  • What happens if the order of the handlers were
    reversed and a FileNotFoundException was
    generated?

24
Specifying the Exceptions Thrown by a Method
  • Sometimes, its better to let a method further up
    the call stack handle the exception.
  • In this case, its better to not catch the
    exception and to allow a method further up the
    call stack to handle it.
  • To forward an exception, use the throws keyword
    in the method declaration in which the exception
    may occur
  • public void writeList() throws IOException
  • The throws clause comprises the throws keyword
    followed by a comma-separated list of all the
    exceptions thrown by that method.

25
How to Throw Exceptions
  • Before you can catch an exception, some code
    somewhere must throw one.
  • Any code can throw an exception. For example
  • Your code,
  • Code in the java packages platform,
  • The Java runtime environment.
  • Exceptions are always thrown with the throw
    statement.
  • throw someThrowableObject

26
How to Throw Exceptions Example
  • public Object pop()
  • . . .
  • if (size 0)
  • throw new EmptyStackException()
  • . . .
Write a Comment
User Comments (0)
About PowerShow.com