Exceptions - PowerPoint PPT Presentation

1 / 24
About This Presentation
Title:

Exceptions

Description:

unchecked exceptions they can occur at many points in the program and recovery ... Unchecked exceptions are of type RuntimeException and its subclasses and Error ... – PowerPoint PPT presentation

Number of Views:52
Avg rating:3.0/5.0
Slides: 25
Provided by: mathew
Learn more at: http://www.cs.ucf.edu
Category:

less

Transcript and Presenter's Notes

Title: Exceptions


1
Exceptions
  • Handling Errors in Java Programs

2
Exceptions
  • When a program violates the semantic constraints
    of the Java programming language, the Java
    virtual machine signals this error to the program
    as an exception.
  • Or to put it another way, an exception is an
    event that occurs during the execution of a
    program that disrupts the normal flow of
    instructions.

3
Why We Need Exceptions
  • Illustrative Example
  • readFile
  • open the file
  • determine its size
  • allocate that much memory
  • read the file into memory
  • close the file

4
Example Exceptions
  • ArrayIndexOutOfBoundsException thrown when you
    attempt to access an array element outside the
    valid range
  • NullPointerException thrown when you attempt to
    access a member or call a method on a variable
    that is not bound to an object

5
The Exception Process
  • When an error occurs inside a method, the method
    creates an exception object and hands it off to
    the runtime system.
  • The exception object contains information about
    the exception.
  • The runtime system is then required to find some
    code to handle the exception.
  • The possible code that can handle the exception
    exists in the call stack.

6
The Exception Process
  • The runtime system searches backward in the call
    stack, beginning with the current method, until
    it finds a method with the appropriate exception
    handler.
  • An exception handler is appropriate if it
    contains a catch clause (of a try statement) that
    catches that particular type of exception (or one
    of its subclasses).

7
Throwing and Catching
  • An exception is said to be thrown from the point
    where it occurred and is said to be caught at the
    point to which control is transferred.

8
try-catch-finally
  • try
  • // open and read from file
  • catch (IOException e)
  • // if file doesnt exist or
  • // problem reading
  • finally
  • // close the file

9
try-catch-finally
  • In the try block, you attempt to execute code
    that could possibly throw exceptions
  • In the catch clause, you handle the executions
    that may get thrown within the try clause
  • In the finally clause, you execute anything that
    needs to be executed regardless of whether or not
    the try ended without exceptions

10
try-catch-finally
  • The parameter of the catch clause, matches just
    like other parameters match any class of the
    type specified or any of its subtypes are valid.
  • For example, in the previous example we caught an
    IOException. FileNotFoundException is a subclass
    of IOException. If FileNotFoundException were
    thrown in the try clause, we would catch it.

11
try-catch-finally
  • The call stack propagation will continue until
    the main method is reached. If no code in the
    main method handles the exception, the program
    terminates.

12
try-catch-finally
  • The finally clause statements are executed
    unconditionally regardless of whether or not an
    exception occurs in the try clause. If an
    exception occurs and no catch clause exists to
    handle it, we execute the finally clause and
    allow the call stack propagation to continue.

13
2 Types of Exceptions
  • checked exceptions checked at compile time you
    must either catch checked exceptions or declare
    the method to throw them
  • unchecked exceptions they can occur at many
    points in the program and recovery from them is
    difficult or impossible

14
Unchecked Exceptions
  • Unchecked exceptions are of type RuntimeException
    and its subclasses and Error and its subclasses

15
Exception Hierarchy
16
Example try-catch
  • A NumberFormatException is thrown when the String
    passed to Integer.parseInt() doesnt contain an
    integer.
  • It is in fact a RuntimeException but sometimes we
    would like to catch this exception and deal with
    it.
  • Example When we have a GUI textbox that should
    accept only an integer, we can catch
    NumberFormatExceptions when parsing the input and
    display a dialog stating that the input is
    invalid.

17
Example try-catch
  • public static void main(String args)
    throws IOException
  • BufferedReader stdin new BufferedReader(new
    InputStreamReader(System.in))
  • System.out.print("Please enter your age ")
  • System.out.flush()
  • String line stdin.readLine()
  • int age 0
  • try
  • age Integer.parseInt(line)
  • catch (NumberFormatException e)
  • System.out.println("You didn't enter
  • a valid integer!")

18
Creating Exceptions
  • All exceptions are subclasses of the class
    Throwable.
  • Typically, you subclass Exception (which is a
    subclass of Throwable).
  • It is a good practice to append the word
    Exception to any exception classes that you
    create.

19
throw statements
  • Programs can also throw exceptions explicitly,
    using throw statements.
  • Explicit use of throw statements provides an
    alternative to the old-fashioned style of
    handling error conditions by returning funny
    values, such as the integer value -1 where a
    negative value would not normally be expected.

20
Example
  • The next 3 slides are part of the same example.
  • The steps in this example should be repeated if
    you find yourself coding methods in which the
    normal flow of execution could be interrupted.
  • You should reuse existing exception classes if
    they are appropriate. Otherwise, create your own.

21
1. Creating An Exception Class
  • Lets create an exception that can be thrown in
    the case that the catchIt method of the
    Juggleable interface cant be completed
    successfully.
  • public class JuggleException extends Exception
  • public JuggleException(String message)
  • super(message)

22
2. Declaring A Throwing Method
  • interface Juggleable
  • void tossIt()
  • void catchIt() throws JuggleException

23
3. Implementing The Method
  • public class Knife implements Juggleable
  • public void tossIt()
  • ...
  • public void catchIt() throws JuggleException
  • ...
  • if (couldn't catch it)
  • throw new JuggleException("You dropped
    it!")

24
Sources for this material
  • Java Language Specification, Second Edition.
    http//java.sun.com/docs/books/jls/second_edition/
    html/exceptions.doc.html
  • The Java Tutorial Handling Errors with
    Exceptions. http//java.sun.com/docs/books/tutoria
    l/essential/exceptions/index.html
  • Execution of a try-catch-finally.
    http//java.sun.com/docs/books/jls/second_edition/
    html/statements.doc.html236653
Write a Comment
User Comments (0)
About PowerShow.com