Exceptions - PowerPoint PPT Presentation

1 / 20
About This Presentation
Title:

Exceptions

Description:

Know how to design custom Exception classes and throw exceptions of various types ... throw new MyException('Niagra Falls...'); Catching I/O Exceptions ... – PowerPoint PPT presentation

Number of Views:158
Avg rating:3.0/5.0
Slides: 21
Provided by: drtimm8
Category:

less

Transcript and Presenter's Notes

Title: Exceptions


1
Exceptions
  • Dr. Tim Margush
  • University of Akron

2
Goals
  • Understand exception handling and Exception
    objects in Java
  • Know how to design custom Exception classes and
    throw exceptions of various types
  • Learn how, when, and where to catch exceptions

3
A Max Method
  • int max(int a)
  • The max method returns the maximum int found in
    an array of int's
  • Precondition the array is not empty
  • If the precondition was not met, a 0 is returned
  • Do you see any problems with this?

4
A Max Method
  • int max(int a)
  • The max method returns the maximum int found in
    an array of int's
  • Precondition the array is not empty
  • If the precondition was not met, a 0 is returned
  • Do you see any problems with this?

1. What if the largest int is a zero?
(click for problems)
2. What if the application uses the returned
value without checking if a zero was returned?
5
Exceptions
  • Exceptions occur when normal processing must be
    interrupted due to exceptional circumstances
  • Division by zero
  • Illegal array index
  • Attempt to dereference a null
  • Requesting the maximum value from an empty array
  • Exceptions cannot be overlooked
  • Code to handle an exception can be decoupled from
    the code where the exception occurs

6
Throwing an Exception
  • Throwing an exception requires creating an
    exception object, and throwing it
  • The method is immediately interrupted when the
    throw clause is executed
  • Control is transferred to an appropriate
    exception handler (more on this later)
  • if (numItems0)
  • throw new NoSuchElementException("Array is
    empty")
  • //continue normal processing

7
Checked and Unchecked
  • Exceptions fall into one of two classes
  • Checked exceptions are required to be attended to
    in your code
  • Either provide exception handling code or throw
    the exception out of the current class
  • The compiler checks that you comply!
  • Unchecked exceptions may be handled in your
    classes, but the compiler does not require this
  • These exceptions, if thrown, will cause a stack
    trace and possible program termination if they
    are not handled in your program

8
Exception Hierarchy
Throwable
  • Error objects are thrown under unrecoverable
    circumstances and cause program termination

Error
Exception
IOException
ClassNotFoundException
CloneNotSupportedException
RuntimeException
  • All Error and RuntimeException exceptions are
    unchecked
  • The other Exception types are checked
  • Checked means the compiler checks that you have
    taken care in your program to account for these
    kinds of exceptions

9
Using java.io
  • Methods must deal with checked exceptions
  • FileReader constructor FileNotFoundException
    (subclass of IOException)
  • readLine method IOException
  • Must be caught or thrown up (to the next level)

public static void main(String args) throws
IOException BufferedReader r new
BufferedReader( new FileReader("afile.txt")
) int num Integer.parseInt(r.readLine())
10
Using java.io
  • Unchecked exceptions extend RuntimeException
  • Integer.parseInt can throw this type of exception
  • You need not put any exception handling code in
    for unchecked exceptions

public static void main(String args) throws
IOException BufferedReader r new
BufferedReader( new FileReader("afile.txt")
) int num Integer.parseInt(r.readLine())
11
Using java.io
  • RuntimeException is the parent of the unchecked
    exceptions

Click for more info
12
Multiple Exceptions
  • If you need to list more than one exception type
    in the throws clause, use a comma

public int readNum () throws
IOException, NumberFormatException
BufferedReader r new BufferedReader(new
FileReader("afile.txt") ) return
Integer.parseInt(r.readLine())
13
Catching Exceptions
  • try
  • one or more statements
  • that can throw exceptions
  • catch (ExceptionClass e)
  • statements
  • catch(OtherExceptionClass e)
  • statements
  • finally
  • statements
  • Checked exceptions must be thrown or caught
  • Catching exceptions is done through the use of
    the try statement inserted at a strategic
    location
  • An exception thrown inside the try block will
    transfer to the first catch block with a
    compatible exception class
  • An optional finally clause will always be
    executed even if no exception occurs

14
Custom Exceptions
  • Creating custom exceptions is as simple as
    extending an exception class
  • Here a custom unchecked exception is declared
  • Throwing is easy
  • public class MyException
  • extends RuntimeException
  • //usually include 2 constructors
  • public MyException()
  • public MyException(String msg)
  • super(msg)

throw new MyException("Niagra Falls")
15
Catching I/O Exceptions
  • The FileNotFoundException and IOException will be
    caught in the first catch block
  • A format error will be caught in the second
  • This case allows execution to continue with num
    -1
  • Try blocks generally enclose groups of statements

16
Finally?
  • The finally clause is guaranteed to be executed
  • 1. When an uncaught exception occurs that will
    need to be thrown upwards to the caller
  • No catch phrases in this example

public static void main(String args) throws
IOException FileReader fr null try
fr new FileReader("afile.txt") )
BufferedReader r new
BufferedReader(fr) int num
Integer.parseInt(r.readLine()) //Look ma! No
catch blocks! finally //always close file
try if (fr!null)fr.close()
catch(IOException e) //go on only if no
exception
17
Finally?
  • The finally clause is guaranteed to be executed
  • 2. after an exception is caught and the last
    statement in a catch block is executed

public static void main(String args) throws
IOException try int num
Integer.parseInt(r.readLine()) catch
NumberFormatException e) num -1
finally sum num
18
Finally?
  • The finally clause is guaranteed to be executed
  • 3. after the last statement in the try block
    executes successfully

public static void main(String args) throws
IOException FileReader fr null try
fr new FileReader("afile.txt") )
BufferedReader r new
BufferedReader(fr) int num
Integer.parseInt(r.readLine()) finally
//always close file try if
(fr!null)fr.close() catch(IOException
e) //go on if no exception
19
Exception Messages
  • Exception objects contain an error message that
    can be retrieved via the getMessage() method
    (which returns a String)
  • To aid debugging, a stack trace can be generated
    from your code using the printStackTrace() method
    which is inherited by all Exception objects.

20
Summary
  • Exceptions cause immediate transfer of control
  • to a catch block if present
  • to a finally clause if present
  • to the caller, terminating current method
  • Exceptions can be thrown to indicate exceptional
    circumstances
  • The compiler requires all checked exceptions to
    be accounted for in your code
Write a Comment
User Comments (0)
About PowerShow.com