Savitch Java Ch. 8 - PowerPoint PPT Presentation

1 / 21
About This Presentation
Title:

Savitch Java Ch. 8

Description:

Following method can throw a DivideByZeroException (not caught in this method) ... Every exception thrown should eventually be caught in some method ... – PowerPoint PPT presentation

Number of Views:88
Avg rating:3.0/5.0
Slides: 22
Provided by: LewRa5
Category:
Tags: caught | java | savitch

less

Transcript and Presenter's Notes

Title: Savitch Java Ch. 8


1
TOPIC 11
Exception Handling
  • Defining Your Own Exception Class
  • Using Exception Classes
  • (Passing the Buck)

2
Creating Your Own Exception Classes
  • Exception class you define extends class
    Exception or one of its subclasses
  • Syntax to throw your own exception object
  • throw new ExceptionClassName(messageString)

3
DEFINING A NEW EXCEPTION
  • class yourExceptionName extends Exception
  • public yourExceptionName()
  • super(meaningful message)
  • public yourExceptionName(String s)
  • super(s)
  • ..

4
Now have an exception class called
yourExceptionName we can throw exception
objects of this class in
  • throw new yourExceptionName(message)
  • catch(yourExceptionName e)
  • do something with e.getMessage()

5
Defining Your Own Exception Classes
public class DivideByZeroException extends
Exception public DivideByZeroException()
super("Dividing by Zero!")
public DivideByZeroException(String message)
super(message)
For example Display 8.3/page 417
  • Must be derived from some already defined
    exception class
  • Often the only method you need to define is the
    constructor
  • Include a constructor that takes a String message
    argument
  • Also include a default constructor with a call to
    super and default message string

6
When to DefineYour Own Exception Class
  • When you use a throw-statement in your code you
    should usually define your own exception class.
  • Will be able to see if your exception was thrown
    OR those by pre-defined classes

7
Exceptions that might be thrown when a method is
invoked, must be accounted for in 1 of 2 ways
  • Possible exception can be caught in a catch block
    within the method definition.
  • Possible exception can be declared at start of
    method definition (throws clause) letting
    whoever uses the method worry about how to handle
    the exception.

8
Example Using the Divide- ByZero- Exception
Class
Excerpt from DivideByZero-ExceptionDemo
8
Chapter 8
Java an Introduction to Computer Science
Programming - Walter Savitch
9
  • public class DoDivision
  • private int numerator
  • private int denominator
  • private double quotient
  • public static void main(String args)
  • DoDivision doIt new DoDivision()
  • try
  • doIt.normal()
  • catch(DivideByZeroException e)
  • System.out.println(e.getMessage())
  • doIt.secondChance()
  • System.out.println("End of Program.")

10
Following method can throw a DivideByZeroException
(not caught in this method). Need to declare
this in a throws clause at start of the
definition of this method.
  • public void normal() throws DivideByZeroException
  • System.out.println("Enter numerator")
  • numerator Integer.parseInt(keyboard.readLine()
    )
  • System.out.println("Enter denominator")
  • denominator Integer.parseInt(keyboard.readLine
    ())
  • if (denominator 0)
  • throw new DivideByZeroException()
  • quotient numerator/(double)denominator
  • System.out.println(numerator "/"
    denominator
  • " " quotient)

11
  • public void secondChance()
  • System.out.println("Try Again")
  • System.out.println("Enter numerator")
  • numerator Integer.parseInt(keyboard.readLine()
    )
  • System.out.println("Enter denominator")
  • System.out.println(Denominator may not be
    zero.")
  • denominator Integer.parseInt(keyboard.readLine
    ())
  • if (denominator 0)
  • System.out.println(Cannot do division by
    zero.")
  • System.out.println(Cannot do what you
    want,")
  • System.out.println("the program will now
    end.")
  • System.exit(0)
  • quotient ((double)numerator)/denominator
  • System.out.println(numerator "/"
    denominator
  • " " quotient)

12
  • PROPOGATING ERRORS
  • Catching an Exception in a Method other than the
    One that Throws It
  • When defining a method you must include a
    throws-clause to declare any exception that might
    be thrown but is not caught in the method.
  • Use a throws-clause to "pass the buck" to
    whatever method calls it (pass the responsibility
    for the catch block to the method that calls it)
  • that method can also pass the buck,but
    eventually some method must catch it
  • This tells methods other methods
  • "If you call me, you must handle any exceptions
    that I throw."

13
Forwarding an Exception with throws
  • Method header (possibly_some-params) throws
    ExceptionType
  • E.g. public static void main(String args)
  • throws IOException
  • Declared at the start of the method definition
  • When a method calls another method that throws an
    exception, it may pass the exception to its own
    caller rather than catch the exception
  • throws clause can contain more than one exception
    type (separated by commas)

14
Example throws-Clause
  • DoDivision
  • It may throw a DivideByZeroException in the
    method normal
  • But the catch block is in main
  • So normal must include a throws-clause in the
    first line of the constructor definition
  • public void normal() throws DivideByZeroException

15
More about Passing the Buck
  • Good programming practice
  • Every exception thrown should eventually be
    caught in some method
  • Normally exceptions are either caught in a catch
    block or deferred to the calling method in a
    throws-clause
  • If a method throws an exception, it expects the
    catch block to be in that method unless it is
    deferred by a throws-clause
  • if the calling method also defers with a
    throws-clause, its calling program is expected to
    have the catch block, etc., up the line all the
    way to main, until a catch block is found

16
Uncaught Exceptions
  • In any one method you can catch some exceptions
    and defer others
  • If an exception is not caught in the method that
    throws it or any of its calling methods, either
  • the program ends, or,
  • in the case of a GUI using Swing, the program may
    become unstable

17
Multiple Exceptions andcatch Blocks in a Method
  • Methods can throw more than one exception
  • The catch blocks immediately following the try
    block are searched in sequence for one that
    catches the exception type
  • the first catch block that handles the exception
    type is the only one that executes
  • Specific exceptions are derived from more general
    types
  • both the specific and general types from which
    they are derived will handle exceptions of the
    more specific type
  • So put the catch blocks for the more specific,
    derived, exceptions early and the more general
    ones later

18
Exercise
  • 1. What happens when a throw-statement is
    executed?
  • throw new Exception (Negative number)
  • 2. Correct the following
  • public void doStuff (int n)
  • if (n
  • throw new Exception (Negative number)

19
Exercise
  • 3. What is the output produced by the following
    program?
  • public class CatchDemo
  • public static void main (String args)
  • CatchDemo object new CatchDemo()
  • try
  • System.out.println(Trying)
  • object.sampleMethod()
  • System.out.println(Trying after call)

20
Exercise
  • catch (Exception e)
  • System.out.println(Catching)
  • System.out.println(e.getMessage() )
  • public void sampleMethod() throws Exception
  • System.out.println(Starting sampleMethod)
  • throw new
  • Exception (From sampleMethod with love.)

21
Solution to Exercise
  • 1. Control goes from throw to catch block
  • Code in catch block is executed
  • object created is passed as a parameter to catch
    block
  • 2. public void doStuff (int n) throws Exception
  • if (n
  • throw new Exception (Negative number)
  • 3. Trying
  • Starting SampleMethod
  • Catching
  • From SampleMethod with love.
Write a Comment
User Comments (0)
About PowerShow.com