Exceptions and Exception Handling - PowerPoint PPT Presentation

1 / 12
About This Presentation
Title:

Exceptions and Exception Handling

Description:

Throwable errors that can be caught and handled are Exceptions and are divided into ... The catch block will execute only if the ... The exception is caught ... – PowerPoint PPT presentation

Number of Views:144
Avg rating:3.0/5.0
Slides: 13
Provided by: NKU
Category:

less

Transcript and Presenter's Notes

Title: Exceptions and Exception Handling


1
Exceptions and Exception Handling
  • The idea of exceptions was introduced in chapter
    1, here we explore exceptions and exception
    handling in more detail
  • While the book does not have a chapter dedicated
    to this, it is covered off and on and briefly in
    appendix C
  • You might also want to check out chapter 8 of
    your CSC 260 textbook
  • Exception an event of interest that arises
    during the execution of your program
  • These include some types of run-time errors as
    well as user defined events
  • Exception Handler code that executes if an
    exception that it is looking for arises

2
Types of Exceptions
  • Since Exceptions are Objects, they are defined in
    a hierarchy
  • Exceptions are a subtype of Object called
    Throwable
  • There is another class of Throwable called Error
    that contains various errors that can not be
    caught by an exception handler and must result in
    termination of the program
  • Throwable errors that can be caught and handled
    are Exceptions and are divided into
  • RuntimeException
  • Which includes ArithmeticException,
    IndexOutofBoundsException, NullPointerException,
    OutOfMemoryException, CloneNotSupportedException,
    ArrayIndexOutOfBoundsException
  • Others
  • Which include IllegalAccessException,
    NoSuchMethodException and ClassNotFoundException

3
Handling Exceptions
  • In Java
  • Exceptions are Objects
  • Exception Handlers are either sets of code or
    pre-defined methods in various Exception classes
  • As stated in chapter 1, there are three ways to
    handle exceptions
  • Use a try-catch clause
  • Throw an exception to a pre-defined exception
    handler
  • Add throws exception to your class method
  • We can also ignore exceptions which, if they are
    run-time errors, cause your program to terminate
    with an error message
  • We will explore these in more detail, see what
    their consequences are

4
Try-Catch Block
  • This is the best way to handle an exception
    because
  • The try block is a set of code in which an
    exception might arise
  • One or more catch blocks follow a try block and
    will catch a specific type of exception or any
    exception
  • The catch block will execute only if the try
    block produces an exception which is explicitly
    caught by that catch block
  • The try block will terminate upon an exception
    and control transfers to the first catch block
    that catches the exception that arose
  • The catch block can correct the mistake so that
    the program continues, or throw an exception to
    cause the program to terminate
  • A finally clause can be added which will execute
    no matter whether a catch block executed or no
    exception arose
  • After the finally block executes, if it or the
    catch block does not cause the program to
    terminate, execution resumes with the first
    instruction after the try block

5
Example
  • Here we have an example of trying to read from a
    disk file and enter the new item into an array
  • The entire set of code is placed inside a
    try-catch-finally block
  • Exceptions that might arise are
  • NullPointerException in case the array has not
    been instantiated
  • ArrayOutOfBoundsException if the array index is
    out of bounds
  • FileNotFoundException in case the file specified
    does not exist
  • NumberFormatException in case the input value is
    not a number
  • We catch each of these in a separate catch block
    and use a finally clause when done to close the
    file

try BufferedReader infile new
BufferedReader(new FileReader(filename))
ax Integer.parseInt(infile.readLine(
)) catch (NullPointerException
exception) System.out.println(Array not
instantiated) catch (ArrayOutOfBoundsExceptio
n exception) System.out.println (Array
already full, cannot add) catch
(FileNotFoundException exception) infile new
BufferedReader (new InputStreamReader(System.in))
catch (NumberFormatException exception)
ax 0 finally infile.close( )

6
What If No try-catch Block?
  • Note that code which might raise an exception
    does not need to be placed in a try-catch block
  • If not, the exception is propagated to whatever
    method invoked the given method
  • If the methods call was itself placed in a
    try-catch block, the exception is caught there
  • Propagation continues until either
  • The exception is caught
  • There are no more calling methods, in which case
    the program terminates with an error message
    indicating the run-time stacks trace of method
    calls

7
Example of Catching Elsewhere
public class PropagationExample static
public void main(String args)
ExceptionExample ee new ExceptionExample( )
System.out.println(at main)
ee.level1( ) System.out.println(ending
main) public class
ExceptionExample public void level1( )
System.out.println(at level
1) try
level2( )
catch(ArithmeticException ex)
System.out.println(AE at level 1)
ex.printStackTrace( )
System.out.println(ending level 1)
public void level2( )
System.out.println(at level 2) level3(
) System.out.println(ending level 2)
public void level3( )
System.out.println(at level 3) int
result 5 / 0 System.out.println(endin
g level 3)
Output at main at level 1 at level 2
at level 3 AE at level 1 followed by
the stack trace ending level 1 ending main
8
Explicitly Throwing an Exception
  • Try-catch blocks can be tedious because you may
    want to supply a catch block for every possible
    exception
  • Another approach is to search for a condition
    that would cause an exception and explicitly
    throw that exception
  • If an exception is thrown, it is either caught by
    an exception handler elsewhere, or not
  • In either way, the program will terminate and the
    message from the thrown exception will be
    displayed for the programmer to see in order to
    help debug the error
  • Throwing an exception uses the throw instruction

9
Examples
  • Consider that you want to throw an exception if a
    user enters a test score that is not within the
    range of 0 100
  • if (value 100) throw new
    Exception(Users input value out of
    range)
  • Here, we attempt to place a new value into an
    array a at location x, but first check to make
    sure that x is a legal array subscript
  • if(x a.length) throw new
    Exception(Array index x out of bounds)
    else ax value

10
Defining Your Own Exceptions
  • Since Exceptions are Objects, you can define your
    own by extending the Exception class
  • If this exception is thrown, MyNewException is
    invoked
  • This invokes MyNewExceptions parent class
    (called super) which is Exception, passing
    message as a parameter
  • This causes the Exception class to handle the
    exception by printing out the message and
    terminating

public class MyNewException extends Exception
MyNewException(String message)
super(message)
MyNewException problem new
MyNewException(/ error message here /) if
(/ condition which leads to problem goes here
/) throw problem
11
Checked vs. Unchecked Exceptions
  • If a method will explicitly look for an
    exception, and then if found, throw that
    exception, then this is known as a Checked
    Exception
  • If you use a class method that contains a
    checked exception, then you must include some
    form of exception handler in your code that calls
    that method
  • You can place the method call inside of a
    try-catch block where the catch block will
    explicitly catch the exception that the method
    throws
  • Or, you can pass the buck by throwing the
    exception further
  • To do the latter, you include throws
    ExceptionName in your methods header
  • If the method does not explicitly check for an
    exception, then any exception that arises is
    known as an unchecked exception
  • You dont have to do anything in these cases,
    although if the exception arises, your program
    does terminate

12
Example
  • The java.io. package contains a number of useful
    classes which deal with input and output
  • Many of these classes explicitly check for an
    IOException
  • Therefore, these are checked exceptions and you
    must handle such an exception
  • This can be accomplished by adding throws
    IOException to your methods header
  • Or, you can place your code in a try-catch block

try BufferedReader keyboard
new BufferedReader (new InputStreamReader(System.
in)) String x keyboard.readLine(
) catch (IOException exception)
Write a Comment
User Comments (0)
About PowerShow.com