Title: CST252 Network Software Design
1CST252 Network Software Design
- Lecture 5 Exceptions and I/O
2Resources
- Java Tutorial (java.sun.com)
- Essential Java Classes/IO Reading and Writing
- Essential Java Classes/Handling Errors with
Exceptions - Course Website
- users.wmin.ac.uk/lancasd/CCTM91
- Book
- Cay Horstmann and Gary Cornell. Core Java
- Volume 1 chapters 11, 12 (Vol 2 in older editions)
3Admin
- Today - last lecture on general Java
- Phase test next week
- 1300 to 1400 11th March
- Rooms on 4th Floor of A block
- Followed by lecture
- starting at 1430
- on Networking
4Lecture 4 Review
- Inheritance
- Manager extends Employee
- Only need code for differences.
- super keyword
- Interface
- A specification
- Employee implements Comparable
- EmployeeSortTest.java
- ArrayLists (Wrapper classes)
- Sorting and Searching - postponed to today
5L4 Inheritance
- Superclass and subclass
- Polymorphism
- Dynamic Binding
- Object class, final, and abstract keywords
- Using Interfaces
6Quiz
- A) Interface int
- boolean wakeUp()
- B) final class Executive extends Manager
- Executive(....) super(...) sp 0.0
- void NegotiateSeverancePay(double d)
- sp d bonus
- double sp
-
- C) abstract class person
- public abstract String getDescription()
-
- D) class Student extends person
- public String getDescription()
- return a student at Wmin
-
7L5 Exceptions and I/O Overview
- Complete lecture on sorting/searching
- Exceptions and errors
- try, catch blocks
- Files, streams
- text, byte files
8Sorting
- Utility methods in
- java.util.Arrays,
- java.util.Collections
- Arrays of primitive type
- Arrays.sort(int arraytobesorted)
- Arrays.sort(double arraytobesorted)
- Lists (ArrayLists, and other more exotic such as
LinkedList) - Collections.sort(ArrayList altobesorted)
9Sorting Arrays of basic types
- For arrays of primitive types
- int, long, short, char, byte, boolean, float,
double - sort() using Quicksearch algorithm
- import java.util.
- int a new int10000
- // fill array
- Arrays.sort(a)
- See SortTest1.java (and SortTest2.java for
ArrayList version) - An in-place method
10Sorting Arrays/ArrayLists of Objects
- Need some way of comparing the elements which are
now objects - Elements must implement the comparable interface
- or can pass a Comparator to the sort method
- Strings have a default compareTo() method that is
case-sensitive - to override for case-insensitive use a Comparator
11Sorting ArrayLists of Strings
- import java.util.
- ArrayList s new ArrayList()
- s.add(the)
- s.add(quick)
- s.add(brown)
- ...
- Collections.sort(s)
- See SortTest3.java
12Search
- Generally must go though all the elements
- Short cut if the list is sorted - binarysearch
- Must act on something already sorted
- Arrays of primitive type
- int i Arrays.binarySearch(int a,int key)
- Objects need comparable interface
- int i Collections.binarySearch(c, element)
- Returns the index of the matching object, or a
negative number if there is no matching element - Access the matching object using ai or c.get(i)
13L5 Errors and Exceptions
- Exception handling in Java
- Kinds of Exception - hierarchy
- checked and unchecked
- Advertising exceptions with throws
- try catch blocks to deal with exceptions
14Errors
- Bugs in code
- Attempting to open files that do not exist
- Trying network connections without a link
- Expect the program to act sensibly and not just
crash immediately - graceful termination
- return to a safe state and wait for user input
15Exception Handling
- Two logical parts
- Code to detect an error
- Code to return the system to a safe state, or to
terminate gracefully - These bits of code should be in separate places.
- When an error occurs, normal execution terminates
and control is transferred from where the error
occurred to where error-handling code can deal
with the error
16Handling Exceptions
- Try Catch blocks - schematically
- try
-
- code
- more code
-
- catch (ExceptionType e)
-
- handler for this type
-
17Try Catch Blocks
- If any code inside the try block throws an
Exception of the type specified in the catch
clause - The program skips the remainder of the code in
the try block - The code in the handler block is executed
- If no exception is thrown
- The program skips the catch clause
18Various kinds of errors
- User input errors
- wrong format, spelling
- Device errors
- hardware errors, printer may be turned off
- Physical limitations
- hard disk fills up
- Code errors
- a bug in the program
19Catching Multiple Exceptions
- try
-
- code that might throw exceptions
-
- catch (MalformedURLException e1)
-
- handler for this type
-
- catch (UnknownHostException e2)
-
- handler for this type
-
- catch (IOException e3)
-
- handler for all other IO problems
-
20Simplified Java Exception Hierarchy
21Kinds of Exception in Java
- Exceptions are instances of classes derived from
Throwable - Error describes internal errors in Java runtime
system - little you can do, unchecked - RuntimeException You made a programming error,
unchecked - IOException An abnormal situation, checked
22Examples
- ClassNotFoundException eg main()
- ArrayIndexOutOfBoundsException
- OutOfMemoryError the JVM
- ArithmeticException divide by 0
- FileNotFoundException checked IOException
23Checked vs Unchecked
- Some kinds of error can be forseen but are not
under your control, such as the IOExceptions, for
these, the compiler insists that you supply a
handler, and will complain if you dont. These
are known as checked exceptions. - For other, unchecked exceptions, you have the
choice of supplying a handler or not.
24Which exceptions to catch?
- Checked exceptions
- the compiler insists that you provide a handler
- the kind of exception a method may throw is
advertised in the header of the method and
documentation - readLine() throws IOException
- Not internal Java errors inheriting from Error
- Put time into fixing RuntimeException errors
rather than catching them - the fact they occur
is your fault
25Propagating Exceptions
- Instead of try catch at this level, leave
(propagate) to whoever uses the method. - public void read(BufferedReader reader) throws
IOException -
- boolean done false
- while(!done)
-
- String line reader.readLine()
- if (line null) //EOF
- done true
- else
- ... // process line
-
-
26Using Exceptions
- Making your own exceptions or methods that throw
predefined exceptions - Performance - do not overuse
- ExceptionalTest - timing results
- Do not wrap every statement in a separate try
block - big unreadable code
- Do not ignore exceptions
- catch( Exception e) // bad
- Propagating exceptions is OK
27L5 I/O Overview
- Streams
- Generality of I/O
- Bytes versus higher level (doublesetc)
- I/O class hierarchy
- Layering of functionality
- IOExceptions are checked and must be handled
28Streams
- A stream of electrical (optical) impulses, a
stream of bits from - read head of a disk
- a network connection
- a microphone
- a camera
- Treat files and network connections similarly
29Binary Streams from Files
- File input from a disk file using FileInputStream
- Give the file name in constructor
- FileInputStream fin new FileInputStream(employe
e.dat) - Then can read bytes
30Binary Streams from Network
- Sockets or URL connections
- Similar syntax to file case
- URL url new URL(protocolresource)
- InputStream uin url.openStream()
- Then can read bytes
31Text/Binary Formats
- Two fundamentally different ways of storing data
- For example the integer 12345 as
- text (chars) 1 2 3 4 5
- binary (bytes) 0 0 48 57 (since
123454825657) - Java has two hierarchies of classes to deal with
each situation - text Reader and Writer class hierarchy
- binary InputStream, OutputStream etc
32Reading Char/Byte Streams
- Low level facilities allow you to look directly
at the byte stream - Reader reads single characters
- public int read() //reads next char (as int
0-65535) - InputStream reads single bytes
- public int read() //reads next byte (as int
0-255) - Read as an int so that it can return -1 when you
get to the end of the stream - Also write methods
33Higher level I/O
- Rarely program at the level of chars/bytes
- Use layering to obtain more convenient interfaces
- pass an existing stream into the constructor of
another, with different capabilities - eg Rather than read bytes, want to assemble them
to read at a higher level - DataInputStream combines bytes into numeric
types - eg Buffered streams (efficiency)
34Layering Streams
- FileInputStream retrieves bytes from a file
- DataInputStream assembles bytes into more useful
forms
- Combine the functionalities
- FileInputStream fin new FileInputStream(employe
e.dat) - DataInputStream din new DataInputStream(fin)
- double x din.readDouble()
35Reading and Writing Text
- Concentrate on this
- Reader and Writer hierarchies
- To attach a file to a reader/writer FileReader
and FileWriter - FileWriter out new FileWriter(output.txt)
- FileReader in new FileReader(input.txt)
- To read keystrokes from the console
InputStreamReader in new
InputStreamReader(System.in)
36Writing Text
- To write Strings (rather than chars) layer
- Combine a PrintWriter with a FileWriter
- PrintWriter out new PrintWriter
- (new FileWriter(employee.txt))
- out.println(Harry hacker)
- double salary 34000
- out.println(salary)
- Use the same println and print methods that you
are familiar with from System.out (System.out is
a PrintWriter class)
37End of Line characters
- The character used to signify the end of a line
is different on different platforms - Windows \r\n
- UNIX \n
- Mac \r
- println() automatically picks the right one
- Obtain using System.getProperty(line.separator)
- Similar call for directory separator
38Reading Text
- Use the readline() method of the BufferedReader
class - BufferedReader in new BufferedReader
- (new FileReader(employee.txt))
- String line
- while ((line in.readLine()) ! null)
-
- //do something with line
-
- Returns a String, use Integer.parseInt() etc to
change to numeric datatype - Returns null when there is no more data
- Must catch IOExceptions
39Typical code for reading a file
- try
-
- BufferedReader in new BufferedReader
- (new FileReader(myfile.txt))
- boolean done false
- while(!done)
-
- String line in.readLine()
- if (line null) //EOF
- done true
- else
- ... // process line
-
-
- catch(IOException e)
-
- e.printStackTrace()
-
40StringTokenizer
- When reading with readLine(), each line is
returned as one long string - Often want to split it into smaller individual
strings (parsing) - Use the StringTokenizer helper class
- Split on delimiters (blank space, commas, ...)
- Get individual strings with nextToken() method
41Delimited text
- Store employee records as
- Harry Hacker355001989101
- Carl Cracker7500019871215
- Tony Tester380001990315
- Break up lines with
- StringTokenizer t new StringTokenizer(line,)
- Use nextToken() method
- name t.nextToken()
- salary Double.parseDouble(nextToken())
- int y Integer.parseInt(nextToken())
- DataFileTest.java
42An Object Oriented Approach
- Want to save objects
- Not all of the same type, some Employees, some
Managers - Could save
- type of object
- data defining the object
- Object serialization does this for you
43Serialization
- ObjectOutputStream out new ObjectOutputStream
- (new FileOutputStream(employee.dat)
- Employee harry new Employee(Harry
Hacker,50000,1989,10,1) - Manager boss new Manager(Carl
Cracker,75000,1987,1,13) - out.writeObject(harry)
- out.writeObject(boss)
- When reading back in, cast to correct type
- Any class that you want to save in this way must
implement Serializable
44More
- Files and directories
- creating files
- Flush
- sometimes want to explicitly ensure that data is
actually written (from possible buffers) to file - Serialized objects
- file format
- object reference problem
45Packages and jar