Exception Handling - PowerPoint PPT Presentation

1 / 53
About This Presentation
Title:

Exception Handling

Description:

tries to add in a number in an incorrect format, ... Button addButton = new Button('Add In'); addButton.addActionListener(this) ... – PowerPoint PPT presentation

Number of Views:47
Avg rating:3.0/5.0
Slides: 54
Provided by: JunN
Category:

less

Transcript and Presenter's Notes

Title: Exception Handling


1
Exception Handling
  • Exception handling is a very important step to
    avoid unexpected errors in some special
    conditions.
  • Exception can be handled through displaying a
    message when something unusual happens, either
    using built-in exception classes or your own
    exception coding

2
Exception Handling
  • First, let's discuss about what is Java exception
  • Example

System.out.println("Enter the mileage
number") double distanceSavitchIn.readDouble()
System.out.println("Enter the driving speed
(m/h)") double speedSavitchIn.readDouble() dou
ble timedistance/speed System.out.println("It
takes about " time" hours" to get
there.")
What happens if speed input is 0?
3
Exception Handling
  • Exception handling can be divided into two steps
    throwing exception and handling exception
  • Throwing an exception using throw in side try
    , called try-block
  • Create an object of Exception
  • Catching the exception in catch, called
    catch-block, in order to show a message
  • Make sure you need to catch the exception
  • It is called try-throw-catch method

4
Exception Handling
  • You can use getMessage() of Exception class to
    accept message thrown over from throw-statement
    in try block.
  • You can even define your own class of Exception
  • The exception class should be inherited from Java
    Exception class
  • Example without exception handling

5
public class GotMilk public static void
main(String args) int donutCount,
milkCount double donutsPerGlass
System.out.println("Enter number of donuts")
donutCount SavitchIn.readLineInt()
System.out.println("Enter number of glasses of
milk") milkCount SavitchIn.readLineInt
() if (milkCount lt 1)
System.out.println("No Milk!")
System.out.println("Go buy some milk.")
System.out.println("Program aborted.")
System.exit(0)
6
donutsPerGlass donutCount/(double)milkC
ount System.out.println(donutCount "
donuts.") System.out.println(milkCount
" glasses of milk.") System.out.println("
You have " donutsPerGlass
" donuts for each glass of milk.")
System.out.println("Press
enter key to end program.") String
junk junk SavitchIn.readLine()
Rewrite the code in the following with exception
handling.
7
public class ExceptionDemo public static
void main(String args) int donutCount,
milkCount double donutsPerGlass
try System.out.println("Ente
r number of donuts") donutCount
SavitchIn.readLineInt()
System.out.println("Enter number of glasses of
milk") milkCount
SavitchIn.readLineInt() if
(milkCount lt 1) throw new
Exception("Exception No Milk!")
donutsPerGlass donutCount/(double)milkCount
System.out.println(donutCount "
donuts.") System.out.println(milkCoun
t " glasses of milk.")
System.out.println("You have " donutsPerGlass
" donuts for each
glass of milk.")
8
catch(Exception e)
System.out.println(e.getMessage())
System.out.println("Go buy some milk.")
System.out.println("Program aborted.")
System.exit(0)
System.out.println("Press enter key to end
program.") String junk junk
SavitchIn.readLine()
9
Exception Handling
  • Exception handling separates the normal case from
    the exception case.
  • Define your own exception class.

10
public class DivideByZeroException extends
Exception public DivideByZeroException()
super("Dividing by Zero!")
public DivideByZeroException(String message)
super(message)
11
public class DivideByZeroExceptionDemo
public static void main(String args)
DivideByZeroExceptionDemo oneTime
new DivideByZeroExceptionDemo(
) oneTime.doIt()
System.out.println("Press enter key to end
program.") String junk junk
SavitchIn.readLine()
12
public void doIt() try
System.out.println("Enter numerator")
numerator SavitchIn.readLineInt()
System.out.println("Enter
denominator") denominator
SavitchIn.readLineInt() if
(denominator 0) throw new
DivideByZeroException() quotient
numerator/(double)denominator
System.out.println(numerator "/"
denominator
" " quotient)

13
catch(DivideByZeroException e)
System.out.println(e.getMessage())
secondChance()
//handle exception without throw exception
public void secondChance()
System.out.println("Try Again")
System.out.println("Enter numerator")
numerator SavitchIn.readLineInt()
System.out.println("Enter denominator")
System.out.println("Be sure the denominator is
not zero.") denominator
SavitchIn.readLineInt()
14
if (denominator 0)
System.out.println("I cannot do division by
zero.") System.out.println("Since I
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) private int numerator
private int denominator private double
quotient
15
Exception Handling
  • Any method may possibly throw an exception. This
    warning is called throws clause. That is called
    passing the buck.
  • Example

public void sampleMethod() throws
DivideByZeroException
This mean the invoking this method might throws
a DivideByZeroException
16
public class DoDivision public static void
main(String args) DoDivision doIt
new DoDivision() try
doIt.normal()
catch(DivideByZeroException e)
System.out.println(e.getMessage())
doIt.secondChance()
17
System.out.println("Press enter key to end
program.") String junk junk
SavitchIn.readLine() public void
normal() throws DivideByZeroException
System.out.println("Enter numerator")
numerator SavitchIn.readLineInt()
System.out.println("Enter denominator")
denominator SavitchIn.readLineInt()
if (denominator 0) throw new
DivideByZeroException() quotient
numerator/(double)denominator
System.out.println(numerator "/"
denominator " "
quotient)
18
public void secondChance()
System.out.println("Try Again")
System.out.println("Enter numerator")
numerator SavitchIn.readLineInt()
System.out.println("Enter denominator")
System.out.println("Be sure the denominator is
not zero.") denominator
SavitchIn.readLineInt() if (denominator
0) System.out.println("I
cannot do division by zero.")
System.out.println("Since I cannot do what you
want,") System.out.println("the
program will now end.")
System.exit(0) quotient
((double)numerator)/denominator
19
System.out.println(numerator "/"
denominator
" "
quotient) private int numerator
private int denominator private double
quotient
20
public class DivideByZeroException extends
Exception public DivideByZeroException()
super("Dividing by Zero!")
public DivideByZeroException(String message)
super(message)
21
Exception Handling
  • Multiple throws and catches
  • You can throw many exceptions and catch many
    exceptions
  • Example

22
public class TwoCatchesDemo public static
void main(String args) try
int jemHadar, klingons double
portion System.out.println("En
ter number of Jem Hadar warriors")
jemHadar SavitchIn.readLineInt() if
(jemHadar lt 0) throw new
NegativeNumberException("Jem Hadar")
System.out.println("How many Klingon warriors do
you have?") klingons
SavitchIn.readLineInt() if (klingons lt
0) throw new NegativeNumberException(
"Klingons")
23
portion exceptionalDivision(jemHadar,
klingons) System.out.println("Each
Klingon must fight "
portion " Jem Hadar.")
catch(DivideByZeroException e)
System.out.println("Today is a good day to
die.") catch(NegativeNumberExceptio
n e) System.out.println("Cannot
have a negative number of "
e.getMessage())
24
System.out.println("End of program.")
System.out.println("Press enter
key to end program.") String junk
junk SavitchIn.readLine() public
static double exceptionalDivision(double
numerator, double
denominator) throws DivideByZeroException
if (denominator 0) throw new
DivideByZeroException() return
(numerator/denominator)
25
public class NegativeNumberException extends
Exception public NegativeNumberException()
super("Negative Number
Exception!") public
NegativeNumberException(String message)
super(message)
26
public class DivideByZeroException extends
Exception public DivideByZeroException()
super("Dividing by Zero!")
public DivideByZeroException(String message)
super(message)
27
Exception Handling
  • Combine AWT and Exception Handling
  • Example

28
import java.awt. import java.awt.event. /

GUI for totaling a series of numbers. If the
user tries to add in a number in an incorrect
format, such as 2,000 with a comma, then an
error message is generated and the user can
restart the computation.
/ public class
ImprovedAdder extends Frame
implements ActionListener public
static final int WIDTH 300 public static
final int HEIGHT 100
29
public static void main(String args)
ImprovedAdder guiAdder new ImprovedAdder()
guiAdder.setVisible(true)
public ImprovedAdder()
setTitle("Adding Machine")
addWindowListener(new WindowDestroyer())
setSize(WIDTH, HEIGHT) setLayout(new
BorderLayout()) Panel buttonPanel new
Panel() buttonPanel.setBackground(Color.g
ray)
30
buttonPanel.setLayout(new FlowLayout())
Button addButton new Button("Add In")
addButton.addActionListener(this)
buttonPanel.add(addButton) Button
resetButton new Button("Reset")
resetButton.addActionListener(this)
buttonPanel.add(resetButton)
add(buttonPanel, "South") Panel
textPanel new Panel()
textPanel.setBackground(Color.blue)
inputOutputField new TextField("Numbers go
here.", 30) inputOutputField.setBackgroun
d(Color.white) textPanel.add(inputOutputF
ield) add(textPanel, "Center")
31
public void actionPerformed(ActionEvent e)
try
tryingCorrectNumberFormats(e)
catch (NumberFormatException e2)
inputOutputField.setText("Error Reenter
Number.") repaint()

32
//This method can throw NumberFormatExceptio
ns. private void tryingCorrectNumberFormats(Ac
tionEvent e) if (e.getActionCommand(
).equals("Add In")) sum
sum stringToDouble(inputOutputFi
eld.getText()) inputOutputField.setTe
xt(Double.toString(sum)) else
if (e.getActionCommand().equals("Reset"))
sum 0
inputOutputField.setText("0.0")
else inputOutputField.setText("Error
in adder code.")
33
//This method can throw NumberFormatExceptio
ns. private static double stringToDouble(Strin
g stringObject) return
Double.valueOf(stringObject.trim()).doubleValue()
private TextField inputOutputField
private double sum 0
34
Exception Handling
  • final block
  • final block is executed whether or not an
    exception is thrown.
  • final block if appended after try-catch-block

try-block catch-block final
35
Exception Handling
  • Another example of calculator

/
PRELIMINARY VERSION without exception
handling. Simple line-oriented calculator
program. The class can also be used to create
other calculator programs.
/ public class
PrelimCalculator public static void
main(String args)
throws DivideByZeroException,
UnknownOpException
36
PrelimCalculator clerk new
PrelimCalculator()
System.out.println("Calculator is on.")
System.out.print("Format of each line ")
System.out.println("operator number")
System.out.println("For example 3")
System.out.println("To end, enter the letter
e.") clerk.doCalculation()
System.out.println("The final result is "
clerk.resultValue())
System.out.println("Calculator program
ending.") System.out.println("Pr
ess enter key to end program.") String
junk junk SavitchIn.readLine()

37
// Added following to catch extra in Windows
8/24/98 RG SavitchIn.readLine()
public PrelimCalculator() result
0 public void reset()
result 0 public void
setResult(double newResult) result
newResult
38
public double resultValue()
return result public void
doCalculation() throws DivideByZeroException,

UnknownOpException char nextOp
double nextNumber boolean done
false result 0
System.out.println("result " result)
while (! done) nextOp
SavitchIn.readNonwhiteChar()
39
if ((nextOp 'e') (nextOp 'E'))
done true else
nextNumber
SavitchIn.readLineDouble()
result evaluate(nextOp, result, nextNumber)
System.out.println("result "
nextOp " "
nextNumber " " result)
System.out.println("updated result "
result)
/
Returns n1 op n2, provided op is one
of '', 'ñ', '',or '/'. Any other value of
op throws UnknownOpException.

/
40
public double evaluate(char op, double n1,
double n2) throws
DivideByZeroException,
UnknownOpException double
answer switch (op)
case '' answer n1 n2
break case '-'
answer n1 - n2 break
case '' answer n1
n2 break case '/'

41
if ( (-precision lt n2) (n2 lt precision))
throw new DivideByZeroException()
answer n1/n2
break default throw
new UnknownOpException(op)
return answer private double result
private double precision 0.0001
//Numbers this close to zero are treated as if
equal to zero.
42
public class DivideByZeroException extends
Exception public DivideByZeroException()
super("Dividing by Zero!")
public DivideByZeroException(String message)
super(message)
43
public class UnknownOpException extends
Exception public UnknownOpException()
super("UnknownOpException")
public UnknownOpException(char op)
super(op " is an unknown operator.")
public UnknownOpException(String
message) super(message)
44
/
Simple line-oriented calculator program.
The class can also be used to create other
calculator programs.
/ public class
Calculator public static void main(String
args) Calculator clerk new
Calculator() try
System.out.println("Calculator is on.")
System.out.print("Format of each line ")
System.out.println("operator number")
System.out.println("For example
3") System.out.println("To end,
enter the letter e.")
clerk.doCalculation()
45
catch(UnknownOpException e)
clerk.handleUnknownOpException(e)
catch(DivideByZeroException e)
clerk.handleDivideByZeroException(e)
System.out.println("The
final result is "
clerk.resultValue())
System.out.println("Calculator program
ending.") System.out.println("Pr
ess enter key to end program.") String
junk junk SavitchIn.readLine()
// Added following to catch extra
SavitchIn.readLine()
46
public Calculator() result
0 public void reset()
result 0 public void
setResult(double newResult) result
newResult public double
resultValue() return result
47
/
The heart of a calculator. This does not
give instructions. Input errors throw
exceptions.
/ public void doCalculation()
throws DivideByZeroException,
UnknownOpException
char nextOp double nextNumber
boolean done false result 0
System.out.println("result " result)
while (! done) nextOp
SavitchIn.readNonwhiteChar() if
((nextOp 'e') (nextOp 'E'))
done true
48
else
nextNumber SavitchIn.readLineDouble()
result evaluate(nextOp, result,
nextNumber) System.out.println("r
esult " nextOp " "
nextNumber " " result)
System.out.println("updated result "
result)
/
Returns n1 op n2, provided op is one
of '', 'ñ', '',or '/'. Any other value of
op throws UnknownOpException.

/ public double evaluate(char op, double
n1, double n2) throws
DivideByZeroException, UnknownOpException
49
double answer switch
(op) case ''
answer n1 n2 break
case '-' answer n1 -
n2 break case ''
answer n1 n2
break case '/' if (
(-precision lt n2) (n2 lt precision))
throw new DivideByZeroException()
answer n1/n2
50
break default
throw new UnknownOpException(op)
return answer public void
handleDivideByZeroException(DivideByZeroException
e) System.out.println("Dividing by
zero.") System.out.println("Program
aborted") System.exit(0)
51
public void handleUnknownOpException(UnknownO
pException e) System.out.println(e.getMessa
ge()) System.out.println("Try again from
the beginning") try
System.out.print("Format of each line ")
System.out.println("operator number")
System.out.println("For example 3")
System.out.println("To end, enter the
letter e.") doCalculation()
catch(UnknownOpException e2)
System.out.println(e2.getMessage())
System.out.println("Try again at some
other time.") System.out.println("Pro
gram ending.") System.exit(0)

52
catch(DivideByZeroException e3)
handleDivideByZeroException(e3)
private double result
private double precision 0.0001 //Numbers
this close to zero are treated as if equal to
zero.
53
Exception Handling
  • Homework Assignment
  • Read chapter 8 of Walter Savitch's textbook
  • Do self-test questions through 1-8, on page
    453-454
  • Do Exercises 1 to 3, on Page 454-456
  • Due date
Write a Comment
User Comments (0)
About PowerShow.com