C Sc 335 4Sep03 More Java from Ch1 Horstmann PowerPoint PPT Presentation

presentation player overlay
1 / 12
About This Presentation
Transcript and Presenter's Notes

Title: C Sc 335 4Sep03 More Java from Ch1 Horstmann


1
C Sc 335 4-Sep-03More Java from Ch1 Horstmann
  • When programs run, exception events occur (a 3rd
    thing that is sure in life).
  • Examples of "exceptional events" include
  • Division by 0
  • Attempt to open and it fails
  • Array subscript out of bounds
  • Trying to convert a string that is not a number
    into a number
  • Can deal with these via exception handling.
  • General form on next slide

2
Handling exceptional events
  • Put code that "throws" exceptional event into a
    try block and add a catch block.
  • try
  • code that cause an exceptional event
    (throws an exception)
  • catch (Exception anException)
  • code that executes when the code in try
    above throws an exception
  • If the code in the try block causes an
    except-ional event, control transfer to the catch
    block.

3
Example
  • ParseDouble may be passed a string that does not
    represent a valid number.
  • String numberAsString depositField.getText()
  • double amount 0.0
  • try
  • // the next message may "throw an exception"
  • amount Double.parseDouble(numberAsString)
  • System.out.println("this may not be sent to
    System.out")
  • catch (NumberFormatException nfe)
  • JOptionPane.showMessageDialog(null,
  • "Not a valid deposit amount"
    numberAsString)

4
parseDouble documentation
  • public static double parseDouble(String s)
  • throws NumberFormatException
  • Returns a number new represented by s
  • Parameters s - the string to be parsed.
  • Returns the double value represented by the
    string argument.
  • Throws NumberFormatException - if the string
    does not represent a valid number, 1o0.0 for
    example.
  • Many methods throw an exception
  • Your methods could also

5
A small piece of Java's large Exception hierarchy
  • Code that throws RuntimeException need not be in
    a try block, All others must be "tried" (there is
    an alternative).

6
Examples of Exceptions
  • parseDouble and parseInt when the String argument
    does not represent a valid number.
  • Integer expressions that result in division by 0.
  • Sending a message to an object when the reference
    variable has the value of null.
  • Indexing exceptions
  • attempting to access an ArrayList element with an
    index that is out of range or a character in a
    string outside the range of 0 through length()-1

7
Two Examples of Exceptions
  • String str null
  • String strAsUpperCase str.toUpperCase()
  • Output
  • Exception in thread "main" java.lang.NullPointerEx
    ception at main(OtherRunTimeExceptions.java6)
  • ArrayList stringList new ArrayList()
  • stringList.add("first")
  • String third (String) stringList.get(1)
  • Output
  • IndexOutOfBoundsException Index 1, Size 1
  • java.util.ArrayList.RangeCheck(ArrayList.java491)
  • at java.util.ArrayList.get(ArrayList.java307)
  • at main(OtherRunTimeExceptions.java10)

8
Throwing your own Exceptions
  • throws and throw are keywords.
  • The object after throw must be an instance of a
    class that extends the Throwable class.
  • public void deposit(double depositAmount)
  • throws IllegalArgumentException
  • // Another way to handle preconditions
  • if (depositAmount lt 0.0)
  • throw new IllegalArgumentException()
  • my_balance my_balance depositAmount

9
Input/Output Streams
  • Input is read through input stream objects.
  • Output is written through output stream objects.
  • A stream is a sequence of items read from some
    source or written to some destination.
  • Let's replace TextReader with standard Java
    classes.

10
Standard input/output
  • Java has two objects for standard I/O
  • System.in The "standard" input stream object (an
    instance of InputStream)
  • System.out The "standard" output stream object
    (an instance of PrintStream)
  • InputStream has readLine
  • PrintStream has all of the print and println
    methods that you have been using
  • print(Object) print(double) print(int)
  • println(Object) println(double) println(int)

11
Standard Input
  • InputStreamReader bytesToChar
  • new InputStreamReader(System.in)
  • // Can only read chars now, so decorate
    bytesToChar
  • // with and instance of BufferedReader so to
  • // get the added funcrtionality of readLine
  • BufferedReader keyboard
  • new BufferedReader(bytesToChar)
  • String line ""
  • System.out.println("Enter a line of text")
  • try
  • // Java forces you to try to read from keyboard
  • line keyboard.readLine()
  • catch (IOException ioe)
  • System.out.println("Couldn't read keyboard")

12
JOptionPane
  • import javax.swing.JOptionPane
  • public class JOption
  • public static void main(String args)
  • String prompt "Enter a number to square"
  • String numberAsString
  • JOptionPane.showInputDialog(null, prompt)
  • double number Double.parseDouble(numberAsStrin
    g)
  • // Note Java also has Integer.parseInt("123")
  • // No user input this time (other than button
    clicks)
  • JOptionPane.showMessageDialog(null,
  • number "2 " Math.pow(number,
    2))
Write a Comment
User Comments (0)
About PowerShow.com