CS242 Advanced Programming Concepts in Java - PowerPoint PPT Presentation

1 / 40
About This Presentation
Title:

CS242 Advanced Programming Concepts in Java

Description:

... result of a programming error, make it a subclass of RuntimeException (unchecked) ... unchecked (array bounds error) system error. Things to remember ... – PowerPoint PPT presentation

Number of Views:124
Avg rating:3.0/5.0
Slides: 41
Provided by: janicets
Category:

less

Transcript and Presenter's Notes

Title: CS242 Advanced Programming Concepts in Java


1
CS242Advanced Programming Concepts in Java
  • 9/13/07
  • exception handling

Prof. Searleman jets_at_clarkson.edu
2
Announcements
  • Clarkson Student Chapter of the ACM
  • organizational meeting on Thursday, 9/13, at 700
    pm in the CEC (Snell 130)
  • IBM mainframe contest starting soon
  • Johnson Johnson peer info session
  • Thursday, 9/13, at 730 p.m. in Snell 214
  • Software Freedom Day 2007
  • This Saturday, 9/15, 11 am 4 pm, in the Applied
    CS Labs (SC334/336)

a horrible death to die
3
Outline
  • Quiz
  • Exception handling
  • Class Design
  • HW2 new due date Thursday, 9/20/07
  • Read OODP, Ch. 7pp.261-280 Effective Java, Ch.
    3pp 25-44

4
Quiz upcasting downcasting note the answers
will not be posted
5
methods toString(), equals(), getClass(),
methods abstract computeArea(), abstract draw(),
aka()
methods constructors, get/setCenter(),
get/setRadius(), computeArea(), toString(),
equals(), compareTo()
methods constructors, get/setColor(),
toString(), equals()
6
Recap What to do when an error is detected?
  • From a users point of view, the program should
  • return to a safe state and allow the user to
    continue
  • or
  • allow the user to save work and then gracefully
    terminate

7
Recap Design for error handling
  • import java.io.
  • public class TestIO
  • public static void main(String args)
  • System.out.print("Enter your account")
  • String buffer String.readLine()

In Java, the class designer MUST design for
potential errors. Some errors can be handled
within the class, but some must be handled in the
application.
8
Recap Checked Exceptions
  • Most application exceptions are checked
  • meaning that the compiler can detect it
  • If you call a method which throws a checked
    exception, you MUST specify to the compiler how
    this will be handled. The choices are
  • (1) propagate (or throw) the exception
  • i.e. the calling code handles it somewhere
  • (2) handle the error at once (try/catch)
  • i.e. take care of it right there

9
Handling exceptions
  • try
  • // stuff
  • catch (SomeException e1 )
  • // do something sensible about
  • // the error

What to do?
  • if caused by user error, give the user a chance
    to correct it
  • take a sensible default action
  • print (or display) an error message where?
  • display pop-up dialog, etc.

10
What to do when an exception occurs?
  • All exceptions inherit the properties methods
    of Throwable
  • useful methods include
  • String getMessage()
  • String toString()
  • void printStackTrace() // backtrace
  • void printStackTrace(PrintStream)
  • tip print to standard error stream
  • System.err.println(system malfunction)

11
Handling exceptions
  • try
  • // stuff
  • catch (SomeException e1 )

System.err.println( e1.getMessage() )
System.err.println( e1.getClass().getName())
e1.printStackTrace( System.err )
12
Example BigInteger
  • Consider the BigInteger class in java.math
  • public class BigInteger / arbitrary precision
    integers /
  • extends Number
  • implements ComparableltBigIntegergt
  • / Returns (this mod m) as a BigInteger
  • _at_param m, the modulus, which must be
    positive
  • _at_return this mod m
  • /
  • public BigInteger mod(BigInteger m)
  • // compute and return (this modulo m)

13
Example BigInteger
  • / application programmer writes the following /
  • public static void main()
  • Random RNG new Random()
  • BigInteger bi new BigInteger(50, RNG)
  • BigInteger ms new BigInteger(0)
  • System.out.println( bi.mod(ms))

ERROR division by zero
14
  • / Returns a BigInteger whose value is (this mod
    m).
  • _at_param m the modulus, which must be positive
  • _at_return this mod m
  • _at_throws ArithmeticException if m lt 0
  • /
  • public BigInteger mod(BigInteger m)
  • throws ArithmeticException
  • if (m.signum() lt 0)
  • throw new ArithmeticException(
  • Modulus not positive)
  • //

15
Item 23 Check parameters for validity.
  • for public methods, use Javadoc _at_throws tag to
    document the exception that will be thrown
    (typically IllegalArgumentException,
    IndexOutOfBoundsException, or NullPointerException
    )
  • nonpublic methods should generally check their
    parameters using assertions

16
  • / application using BigInteger /
  • public static void main()
  • Random RNG new Random()
  • BigInteger bi new BigInteger(50, RNG)
  • BigInteger ms new BigInteger(0)
  • System.out.println( bi.mod(ms) )

PROBLEM wheres the code to handle the error?
Note that the compiler can determine that this is
a problem. How? Because the header for
BigInteger.mod() specifies that it throws an
exception (specifically ArithmeticException)
17
  • public static void main()
  • Random RNG new Random()
  • BigInteger bi new BigInteger(50, RNG)
  • BigInteger ms new BigInteger(0)
  • try
  • System.out.println( bi.mod(ms) )
  • catch (ArithmeticException ex)
  • System.out.println(ex.getMessage())

Application programmer decides what to do print
an error message? let the user try again?
whatever
18
Types of Exceptions
  • if an error is always the result of a programming
    error, make it a subclass of RuntimeException
    (unchecked)
  • if an error is something the application can
    recover from use checked exception class
    (extends Exception)
  • the Error class is effectively reserved for the
    JVM, and is used to indicate resource
    deficiencies, invariant failures and other
    conditions that make it impossible to continue
    execution

19
(No Transcript)
20
(No Transcript)
21
java.io.IOException
MalformedURLException
EOFException
22
Item 42 Favor the use of standard exceptions
  • IllegalArgumentException
  • - parameter value is inappropriate
  • IllegalStateException
  • - object state is inappropriate
  • NullPointerException
  • - parameter value is null where prohibited
  • IndexOutOfBoundsException
  • - index parameter value is out of range

23
  • String
  • public String(byte bytes, int offset,
    int length)
  • Constructs a new String by decoding the specified
    subarray of bytes using the platform's default
    charset.
  • Parameters
  • bytes - the bytes to be decoded into characters
  • offset - the index of the first byte to decode
  • length - the number of bytes to decode
  • Throws
  • IndexOutOfBoundsException - if the offset and the
    length arguments index characters outside the
    bounds of the bytes array

24
Catching Exceptions
  • try
  • // do stuff
  • // more stuff
  • catch(IOException ioe)
  • // handle this case
  • catch(UnknownHostException uhe)
  • // handle this case

25
  • If any of the code inside the try block throws an
    exception of the specified types, then
  • 1. the program skips the remainder of the code in
    the try block
  • 2. the program executes the handler code inside
    the matching catch clause
  • If any of the code inside the try block throws a
    different kind of exception, the method exits
    immediately (presumably the calling code has a
    catch clause for that type)
  • The exception objects, ioe, uhe, contains
    information about the error that occurred. Can
    use this when handling the problem.

26
  • Example Want to write a method, readLine(),
    that reads in a line of text. Algorithm have a
    loop that calls System.in.read() which reads in
    one character.
  • public int read() throws IOException
  • Returns the next byte of data, or -1 if the
  • end of the stream is reached.
  • Throws IOException - if an I/O error occurs.

This is a checked exception, so the method
readLine() must either handle the exception
internally or propagate it externally
27
  • // Alternative 1 propagate the error
  • // (let someone else in the call stack handle it)
  • public static String readLine() throws
    IOException
  • / implement read a line of text /
  • // Alternative 2 handle the error internally
  • public static String readLine()
  • try / implement read a line of test /
  • catch(IOException e)
  • / do something sensible about an I/O
    error /

28
  • // Version 1 if error occurs, propagate the
    error
  • // (loses partial line)
  • public static String readLine() throws
    IOException
  • int ch String r "" boolean done
    false
  • while(!done)
  • ch System.in.read()
  • if ((ch lt 0) (ch '\n'))
  • done true
  • else
  • r r (char)ch
  • return r

29
  • // Test Version 1 of readLine()
  • import java.io.
  • public class TestVersion1
  • // Version 1 if error occurs, propagate the
    error
  • public static String readLine() throws
    IOException
  • public static void main(String args)
  • System.out.print("Enter a line")
  • System.out.println(readLine())

compile error! why?
unreported exception
30
  • // Test Version 1 of readLine(), take 2
  • import java.io.
  • public class TestVersion1
  • // Version 1 if error occurs, propagate the
    error
  • public static String readLine() throws
    IOException
  • public static void main(String args)
  • System.out.print("Enter a line")
  • try
  • System.out.println(readLine())
  • catch(IOException e)
  • System.out.println(e.getMessage())

31
  • // Version 2 if read() fails, return partial
    line
  • public static String readLine()
  • int ch String r "" boolean done
    false
  • while(!done)
  • try
  • ch System.in.read()
  • if (ch lt 0) (char)ch '\n')
  • done true
  • else
  • r r (char)ch
  • catch(IOException e) done true
  • return r

32
  • // Test Version 2 of readLine()
  • import java.io.
  • public class TestVersion2
  • // Version 2 if error occurs, return partial
    line
  • public static String readLine()
  • public static void main(String args)
  • System.out.print("Enter a line")
  • System.out.println(readLine())

no compile error! why not?
33
  • Exception types
  • main() Lamp.init() Magic.castSpell()
  • public class Magic
  • public String castSpell( int n)
  • char ch System.in.read()
  • if (n lt 0)
  • throw new FooException(you idiot)
  • line-1 ch

system error
34
Things to remember
  • Item 40 Use checked exceptions for recoverable
    conditions and run-time exceptions for
    programming errors
  • checked caller can be reasonably be expected
    to recover from this type of error
  • run-time indicates programming errors, such as
    precondition violations, array out of bounds, etc.

35
Things to remember
  • Exception handling is not supposed to replace a
    simple test.
  • try
  • s.pop()
  • catch(EmptyStackException es)
  • if (!s.empty()) s.pop() // is much better

terrible design too much overhead!
36
Things to remember
  • Item 39 Use exceptions only for exceptional
    conditions
  • A well-designed API must not force its client to
    use exceptions for ordinary control flow.

37
Things to remember
  • Do not micromanage exceptions.
  • try s1 catch(Exception e)
  • try s2 catch(Exception e)
  • etc.
  • Item 43 Throw exceptions appropriate to the
    abstraction.

try s1 s2 catch(
catch-all
38
Things to remember
  • Do not squelch exceptions.
  • Image loadImage(String s)
  • try
  • // lots of stuff
  • catch(Exception e) // so there!
  • Item 47 Dont ignore exceptions.

39
Class Design
  • Design principles
  • The importance of encapsulation
  • Analyzing the quality of an interface
  • Programming by contract
  • preconditions, postconditions, invariants
  • cf. OODP, Chapter 3

40
Class Design Hints
  • Keep data private unless theres a good reason to
    do otherwise
  • Always initialize data (dont rely on defaults)
  • Dont use too many primitive types in a class
  • Not all fields need a get and/or set
  • Break up classes that have too many
    responsibilities
  • Use naming conventions
  • ltnoungt for name of class (e.g. class Tile)
  • ltverbgt for method name (e.g. method placeTile() )
  • getltvaluegt for accessor method (e.g. getSize() )
  • setltvaluegt for mutator method (e.g. setSize() )
Write a Comment
User Comments (0)
About PowerShow.com