ET4264 Java Progamming 2

squawkpsychoticΛογισμικό & κατασκευή λογ/κού

2 Δεκ 2013 (πριν από 3 χρόνια και 4 μήνες)

83 εμφανίσεις

1
ET4264
Java Progamming 2
Dr Reiner Dojen
ET4264 – Java Programming 2 1
Dr
.
Reiner

Dojen
Email: reiner.dojen@ul.ie
Phone: 061-213442 (Ext. 3442)
Room: D3002
Why Exception Handling?
• Errors always might happen
• Programs must handle errors
• Problems:
Checking every method call for errors can be tedious
ET4264 – Java Programming 2 2

Checking

every

method

call

for

errors

can

be

tedious
– Insufficient information to fix
– “Cluttered” code
– Programmers might ignore error conditions
• Java structures & enforces error handling through
Exceptions
Advantages of Java Exceptions
• Separates “normal” case from “exceptional” case
=>concentrate on problem first, then handle errors
• Delegates error handling to exception handler

Exceptions can be passed to other program
ET4264 – Java Programming 2 3

Exceptions

can

be

passed

to

other

program

components (e.g. “higher authorities”)
• Exception handling can be enforced
Types of Exceptions
• Checked Exceptions: usually user error or
problem that cannot be foreseen by programmer
(e.g. file not found) – Cannot be ignored

Runtime Exceptions (Unchecked Exception):
ET4264 –Java Programming 2 4
Runtime

Exceptions

(Unchecked

Exception):
usually programmer error (e.g. null pointer, index
out of bounds, division by zero). Can/should be
ignored – on crash fix code
• Errors:usually system errors – nothing can be
done (e.g. stack overflow – out of memory)
Throwable
Error
Exception
ClassNot
Found
Exception
IOException
Unknown
Host
Exception
Malformed
URL
Exception
FileNotFound
Exception
EOF
Exception
ET4264 – Java Programming 2 5
Arithmetic
Exception
Runtime
Exception
CloneNot
Supported
Exception
NullPointer
Exception
NoSuch
Element
Exception
IndexOutOf
Bounds
Exception
Illegal
State
Exception
Illegal
Argument
Exception
ClassCast
Exception
Unchecked
Checked
try-throw-catch Mechanism
• Basic exception setup in Java:
try {
code_that_may_throw_exception or
method invocation throwin
g
ET4264 – Java Programming 2 6
_ _
g
} catch (ExceptionName1 e1) {
code_that_handles_exeption
} catch (ExceptionName2 e2) {
code_that_handles_exeption
}
2
Throwing Exceptions
• Methods must declare (checked) exceptions that they
might throw:
public f() throws IOException {

if (errorcondition)
throw new IOException(

Reason

);
ET4264 – Java Programming 2 7
throw

new

IOException( Reason );

}
• No need to declare Runtime exceptions/errors
• Not catching exception => throwing exception
• Throw exception that describes problem
• No suitable exception available: define new exception by
inheriting from class Exception (or any subclass)
Catching Exceptions
• Every thrown exception must be caught
• Uncaught exception terminates application
• Multiple catch-clauses with different arguments
allowed => catch most specific exception first
ET4264 – Java Programming 2 8
allowed

=>

catch

most

specific

exception

first
• Only catch exceptions you can deal with: “Throw
Early, Catch Late”
• Exceptions can be re-thrown if only part of the
problem can be solved
• Do not squelch exceptions (empty catch block)
Finally - Cleanup
• Throw-clauses can have a finally block
• Used for “cleaning up”, i.e. closing files, network
connections etc.
try {
ET4264 – Java Programming 2 9
PrintWriter out = new
PrintWriter(filename);
writeData(out); // if exception
// occurs file is never closed
out.close();
} catch (IOException e) {…}
Finally (cont)
• Never use catch & finally in same try-block, if
code in finally block can cause exceptions!
try {
PrintWriter out = new
PrintWriter(filename);
ET4264 – Java Programming 2 10
PrintWriter(filename);
writeData(out);
} catch (IOException e) {

} finally {
out.close();
}
Finally (cont)
• Correct use
try {
try {
PrintWriter out = new
PrintWriter(filename);
ET4264 – Java Programming 2 11
PrintWriter(filename);
writeData(out);
} finally {
out.close();
}
} catch (IOException e) { … }
Introduction to Files
• Programs often need to be able to write data and
more often need to be able to read data as well
• So far have read data from the keyboard and
displayed data on the screen
-
data is lost when the
ET4264 – Java Programming 2 12
displayed

data

on

the

screen

data

is

lost

when

the

program terminates
• Usually program need to store data so that it can
be used with other programs and/or subsequent
executions
3
Java and File I/O
• Java uses Streams to handle any I/O
• Hides data source/sink – no matter if writing to
file/memory/string etc.
• Difference only in creating the strea
m
ET4264 – Java Programming 2 13
• Java distinguishes between text files and binary
files
• Text files: use Reader/Writer classes
• Binary files: use Inputstream/Outputstream classes
• Package java.io provides classes for I/O
Reading a Textfile using FileReader
FileReader(File infile)
Constructs reader from a file object
FileReader(String infile)
Constructs reader from String
ET4264 – Java Programming 2 14
(both trow FileNotFoundException)
int read()
Reads a single character (range 0x00-0xffff, -1 on EOF)
void close()
Closes file – may throw IOException
Writing to a Textfile using FileWriter
FileWriter(File outfile)
Constructs writer from a file object, overwrites file
FileWriter(String outfile)
Constructs writer from String, overwrites file
(both trow IOException)
Fil
e
Wri
te
r
(
Fil
e

out
fil
e,

boo
l
ea
n
appe
n
d)
ET4264 – Java Programming 2 15
e te ( e out e,boo ea appe d)
FileWriter(String outfile, boolean append)
Same as above, allow to append
void write(int c)
Writes a single character (range 0x00-0xffff, higher bits ignored)
void close()
Closes file
Both may throw IOException
I/O to Binary Files
• Classes FileInputStream and
FileOutputStream deal with binary I/O
• Only read/write single bytes

Not common in Java as we deal with
Objects
not
ET4264 –Java Programming 2 16

Not

common

in

Java

as

we

deal

with

Objects
not

Bytes (as in non-OOP languages)
• Common to use FileInputStream objects to
create ObjectInputStream objects and
FileOutputStream objects to create
ObjectOutputStream objects
The class FileInputStream
FileInputStream(File infile)
Constructs stream from a file object
FileInputStream(String infile)
Constructs stream from String
ET4264 – Java Programming 2 17
(both trow FileNotFoundException)
int read()
Reads a single byte (range 0x00-0xff, -1 on EOF)
void close()
Closes file – may throw IOException
The Class FileOutputStream
FileOutputStream(File outfile)
Constructs stream from a file object, overwrites file
FileOutputStream(String outfile)
Constructs stream from String, overwrites file
(both trow FileNotFoundException)
F
il
eOutputSt
r
ea
m
(
Fil
e

out
fil
e,

boo
l
ea
n
appe
n
d)
ET4264 – Java Programming 2 18
eOutputSt ea ( e out e,boo ea appe d)
FileOutputStream(String outfile, boolean append)
Same as above, allow to append
void write(int b)
Writes a single byte (range 0x00-0xff, higher bits ignored)
void close()
Closes file
Both may throw IOException
4
Using Object Stream
• Object streams allow to read/write entire objects
• Object streams can be linked to any stream (file,
string, char array, etc.)
• Object streams have method to read native types
ET4264 – Java Programming 2 19
(int, double, char, etc.) and generic objects
• Objects written to object stream must implement
interface java.io.Serializable (has no
methods)
• Attention: Some classes have limited support for
serialization (e.g. swing) – always check API