Chapter 11: Exception Handling - PowerPoint PPT Presentation

1 / 23
About This Presentation
Title:

Chapter 11: Exception Handling

Description:

Creating Your Own Exception Classes (Optional) Exception. An exception represents an error condition that can ... Runtime Exceptions (unchecked exceptions) ... – PowerPoint PPT presentation

Number of Views:93
Avg rating:3.0/5.0
Slides: 24
Provided by: yda50
Category:

less

Transcript and Presenter's Notes

Title: Chapter 11: Exception Handling


1
Chapter 11 Exception Handling
  • Exceptions and Exception Types
  • Claiming Exceptions
  • Throwing Exceptions
  • Catching Exceptions
  • Rethrowing Exceptions
  • The finally Clause
  • Cautions When Using Exceptions
  • Creating Your Own Exception Classes (Optional)

2
Exception
  • An exception represents an error condition that
    can occur during the normal course of program
    execution.
  • An exception is an object that represents an
    error or exceptional event that has occurred
  • array index out of bounds IndexOutOfBoundsExceptio
    n
  • trying to open a file that does not exist
    FileNotFoundException
  • trying to call a method that does not exist
    NoSuchMethodException
  • When an exception occurs, the normal sequence of
    flow is terminated and the exception handling
    routine is executed.
  • When an exception occurs, an exception is thrown,
    when exception handling occurs, the thrown
    exception is caught.

3
Types of Exceptions
  • Normal Exceptions (checked exceptions)
  • These exceptions are the ones that every good
    program should watch for (for example
    FileNotFoundException) you have to handle these
    (either catch them or declare that you method can
    throw them).
  • Runtime Exceptions (unchecked exceptions)
  • These exceptions have the potential to be in all
    code you write (for example IndexOutOfBoundsExcept
    ion) you do not need to handle these.
  • There is a class of exceptions called errors
    these are generally irrecoverable (example
    VirtualMachineError) These exceptions do not need
    to be handled.

4
Exceptions and Exception Types
5
Exception Handling
  • Try, catch, throw, throws and finally
  • Try block contains the program block to monitor
    the exception.
  • If an exception occurs within the try block, it
    is thrown
  • A catch block will catch the exception
  • Finally means the code has absolutely must be
    executed. ie A finally block is ALWAYS executed
    no matter how control leaves a try block. This
    means even if a return statement is executed in
    the try block, and even if control passes to a
    catch block.

6
try lots of IO code opening and reading
from/to files catch (FileNotFoundException)
tell the user and probably repeat try block
catch (EOF Exception) hit the End Of File
marker early catch (IOException) blanket
catch for all other IO problems finally make
sure to close any files that might be open
7
Throws and throw
  • throws exceptions -the compiler and user of the
    code are aware that this method can produce these
    checked exceptions.
  • Example
  • public String wildFileMethod (String fileName)
    throws FileNotFoundException, EOFException
  • code goes here

8
Throw
  • throw -to introduce a new exception .
  • throw an already existing exception type or
    create your own.
  • if (personOnPhone ! babu) throw new
    Exception("Stranger on the phone!!")

9
Claiming, Throwing, and Catching Exceptions
10
Claiming Exceptions
  • public void myMethod()
  • throws IOException
  • public void myMethod()
  • throws IOException, OtherException

11
Throwing Exceptions
  • throw new TheException()
  • TheException e new TheException()throw e

12
Example 1
//demonstrate Exception Example
ArrayIndexOutOfBoundException
Class ExcDemo1 Public static void main(String
args) Int numsnew int4 Try
S.o.p(Before exception is generated.) //gener
ate an index out-of-bounds exception Nums710 s
.o.p(this wont be displayed) Catch(ArrayInde
xOutOfBoundsException e) //catch the
exception s.o.p(Index Out OF Bound error)
Finally System.out.println(After the catch
ststement)
13
Throwing Exceptions Example
  • public Rational divide(Rational r) throws
    Exception
  • if (r.numer 0)
  • throw new Exception("denominator
  • cannot be zero")
  • long n numerr.denom
  • long d denomr.numer
  • return new Rational(n,d)

14
Catching Exceptions
  • try
  • statements
  • catch (Exception1 e)
  • handler for exception1
  • catch (Exception2 e)
  • handler for exception2
  • ...
  • catch (ExceptionN e)
  • handler for exceptionN

15
Catching Exceptions
16
Example 11.1 Claiming, Throwing, and Catching
Exceptions
  • Objective Write a program to test the new
    Rational class.

TestRationalException
Rational
Run
17
Catching subclass Exceptions
  • Class ExDemo2
  • public static void main(String args)
  • int num4,8,16,32,64,128,256,512)
  • int den2,0,4,4,0,8)
  • for (int i0Iltnum.lengthi)
  • try
  • System.out.println(numi/deniis
    numi/deni)
  • Catch(ArrayIndexOutOfBoundsExcpetion e)
  • //catch the exception
  • s.o.p(No matching element found)
  • Catch(Throwable e)
  • s.o.p(Some Exception occurred)

18
Example 11.2 Exceptions in GUI Applications
  • An error message appears on the console, but the
    GUI application continues running.
  • Re-run the MenuDemo applet from Example 9.9 and
    divide by 0 to see how a GUI deals with unhandled
    exceptions.

MenuDemo
Run
19
Rethrowing Exceptions
  • try
  • statements
  • catch(TheException e)
  • perform operations before exits
  • throw e

20
The finally Clause
  • try
  • statements
  • catch(TheException e)
  • handling e
  • finally
  • finalStatements

21
Cautions When Using Exceptions
  • Exception handling separates error-handling code
    from normal programming tasks, thus making
    programs easier to read and to modify. Be aware,
    however, that exception handling usually requires
    more time and resources because it requires
    instantiating a new exception object, rolling
    back the call stack, and propagating the errors
    to the calling methods.

22
Example 11.3 (Optional) Creating Your Own
Exception Classes
  • Objective This program creates a Java applet for
    handling account transactions. The applet
    displays the account id and balance, and lets the
    user deposit to or withdraw from the account. For
    each transaction, a message is displayed to
    indicate the status of the transaction
    successful or failed. In case of failure, the
    failure reason is reported.

23
Example 11.3, cont.
Account
InsufficientFundException
NegativeAmountException
AccountApplet
Run
Write a Comment
User Comments (0)
About PowerShow.com