OOP del II (sista) - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

OOP del II (sista)

Description:

The try/catch/finally statement is Java's exception handling mechanism ... Java provides a tool for modeling a stream of bytes sent to a file as if they ... – PowerPoint PPT presentation

Number of Views:33
Avg rating:3.0/5.0
Slides: 27
Provided by: LARS135
Category:
Tags: oop | del | javas | sista

less

Transcript and Presenter's Notes

Title: OOP del II (sista)


1
OOP del II (sista) vecka 10
  • Catch o Throw och I/O

2
Model catch and throws
  • Exception Model
  • Exception handling is a significant feature from
    Java that other programming languages do NOT have
    (like C and others)
  • There are a number of new terms associated with
    exception handling
  • Exception signal indicating exceptional
    condition
  • To throw an exception is to signal the
    exceptional condition
  • To catch an exception is to handle it, to take
    actions to recover from the exception
  • When we know that a certain part of code could
    generate an exception, we try to execute it, but
    we provide the system with some tools to act if
    it happens

3
Code
  • Exception Model
  • Example
  • try
  • // normally this code runs without problems,
  • // but sometimes may raise exceptions or exit
  • // the block via a break, continue, or return
  • catch (ExceptionType1 e1)
  • // handle an exception object e1 of type
  • // ExceptionType1 or of a subclass of that type
  • catch (ExceptionType2 e2)
  • // handle an exception object e1 of type
  • // ExceptionType2 or of a subclass of that type
  • finally
  • // always execute this code, after leaving the
    try clause
  • // 1) normally, after reaching the bottom of
    the block
  • // 2) with an exception handled by a catch
  • // 3) with an exception that is not handled
  • // 4) because of a break, continue or return
    statement

4
Exception Model subclasses
  • Exception Model
  • An exception in Java is an object that is an
    instance of some subclass of java.lang.Throwable
  • Throwable has two standard subclasses
    java.lang.Error and java.lang.Exception
  • Exceptions that are subclasses of Error generally
    indicate problems that do have NOTHING to do with
    our code, they are related to problems like the
    system running low on virtual memory and other
    problems and therefore SHOULD NOT BE CAUGHT

5
Exceptions example
  • Exception Model
  • Even if it is not so easy to distinguish one from
    the others, exceptions indicate conditions that
    may be caught and recovered from
  • Examples of exceptions are
  • java.io.EOFException indicates the end of a file
  • java.lang.ArrayAccessOutOfBounds indicates that
    a program has tried to read past the end of an
    array

6
Code
  • Exception Model
  • The try/catch/finally statement is Javas
    exception handling mechanism
  • try establishes a block of code that is to have
    its exceptions and normal exits (through break,
    continue, return, or exception propagation)
    handled
  • The try block is followed by a by zero or more
    catch clauses that catch and handle specified
    types of exceptions
  • The catch clauses are optionally followed by a
    finally block that contains clean-up code
  • The statements of a finally block are guaranteed
    to be executed, regardless of how the code in the
    try block exits

7
try
  • Exception Model
  • About try
  • It establishes a block of code that is to have
    its exceptions and abnormal exits handled
  • By itself, the try clause, is not interesting, it
    just generates the problem, but it doesnt look
    for the solution

8
catch
  • Exception Model
  • About catch
  • A try block is followed by zero or more catch
    clauses that specify code to handle various types
    of exceptions
  • Catch clauses have an unusual syntax each is
    declared with an argument, much like a method
    argument. This argument MUST be of type Throwable
    or a subclass
  • When an exception occurs, the first catch clause
    that has an argument of the appropriate type is
    invoked. The type of the argument must match the
    type of the exception object, or it must be a
    superclass of the exception

9
Model I
  • Exception Model
  • Exceptions propagate up through the lexical block
    structure of a Java method, and then up the
    method call stack
  • If an exception is not caught by the block of
    code that throws it, it propagates to the next
    higher enclosing block of code

throws Exception
Method A
Method B
Method C
Method D
EXCEPTION
direction of propagation
10
Model II
  • Exception Model
  • Exceptions make the error handling more logical
    and regular by allowing you to group all the
    exception handling code in only one place instead
    of worrying about all the things that could go
    wrong at each line of the code

throws Exception
Method A
Method B
Method C
Method D
EXCEPTION
main()
ERROR
direction of propagation
exception handling code
11
Model II
  • Exception Model
  • If an exception is never caught, it propagates
    all the way to the main() method from which the
    program started, and causes the Java interpreter
    to print an error message and exit

throws Exception
Method A
Method B
Method C
Method D
EXCEPTION
main()
ERROR
direction of propagation
12
Code
  • Exception Model
  • Example
  • try
  • // normally this code runs without problems,
  • // but sometimes may raise exceptions or exit
  • // the block via a break, continue, or return
  • catch (ExceptionType1 e1)
  • // handle an exception object e1 of type
  • // ExceptionType1 or of a subclass of that type
  • catch (ExceptionType2 e2)
  • // handle an exception object e1 of type
  • // ExceptionType2 or of a subclass of that type
  • finally
  • // always execute this code, after leaving the
    try clause
  • // 1) normally, after reaching the bottom of
    the block
  • // 2) with an exception handled by a catch
  • // 3) with an exception that is not handled
  • // 4) because of a break, continue or return
    statement

13
Filer allmänt
  • Operations with files
  • create programs write data into files
  • delete removes name and contents
  • rename changes name but keeps contents
  • overwrite keeps name but changes contents
  • read reads data from the contents of the file

14
Files Code
Java provides a predefined class for modeling
disk files and directories, called File
the constructor for File accepts the files name
(a String reference) as its argument
new File (filename)
An example of this would be
File f1, f2 f1 new File(Bjorn.txt) f2 new
File(Lisa.txt)
15
Files
DO NOT FORGET THAT The creation of the instances
f1 and f2 doesnt mean that the files exist!!
If the files exist the class provides us two
methods for directly operate with the files
16
OUTPUT
Java program
bytes of data
ewsc24rfds53Hej20Hur20m76ar20du20?rsf
17
OUTPUT Code
Java provides a tool for modeling a stream of
bytes sent to a file as if they were sent to a
screen
the constructor for PrintWriter accepts a
reference to a FileWriter as its argument
new PrintWriter (fileoutputstream)
An example of this would be
File f FileWriter fs PrintWriter target f
new File(data.out) fs new FileWriter(f) targ
et new PrintWriter(fs) target.println(Lisa is
a girl)
18
OUTPUT Code
summary how to create or overwrite a file in a
line
  • Create a File object to represent the file and
    then use it to
  • Create a FileWriter object to represent the
    output pathway to the file and use it to
  • Create a PrintWriter object to provide a
    convenient output pathway to the file
  • Use the print or println methods of PrintWriter
    as needed to write content to the file

PrintWriter target new PrintWriter( new
FileWriter( new File(data.out)))
19
Flush
There is a part of the memory that is allocated
for streaming operations. It is called a buffer.
There the computer stores as many information as
it cans, and shows it at once, when it is full.
string3
string2
string1
buffer
But, there is a method that forces the strings to
be shown .flush() forces the computer to empty
the buffer.
20
INPUT
Input source
Java program
bytes of data
ewsc24rfds53Hej20Hur20m76ar20du20?rsf
We must build a bridge between the Java Program
and the input source!!
21
Input from keyboard overview
Java provides a predefined object to represent
the stream of input that comes from the keyboard
System.in.
keyboard
System.in
isr


existing InputStream
keyb


new InputStreamReader

new BufferedReader
BufferedReader keyb new BufferedReader( new
InputStreamReader(System.in))
22
INPUT from files overview
Obtaining input from disk files is only a little
bit more complicated than from the keyboard. Our
starting point must be to find some sort of
InputStream object. As we said before, both
BufferedReader and FileReader belong to that class
fr
files

br


new FileReader

new BufferedReader
BufferedReader br new BufferedReader( new
FileReader("c/testio.txt"))
23
INPUT from file code
The total declaration would be
File f FileReader
fsr BufferedReader bsr f new
File(myFile.txt) fsr new FileReader(f) bsr
new BufferedReader(isr)
24
Sammanställning
Some InputStream fx System.in URL
FileReader
InputStreamReader
BufferedReader
BufferedReader
program
PrintWriter
FileWriter
25
Torsdag 10/3
  • Nämnden för nätbaserad utbildning inbjuder till
  • Seminarium om Webzone-plattformen som
    utbildningsstöd
  • När och var Torsdagen den 10 mars kl. 14-16 c.a,
    lokal Hörsalen på K3
  • Dels redovisas två projekt som nämnden hjälpt
    till att finanisera, dels får Du möjlighet att
    fråga kollegor om deras erfarenheter av att
    använda Webzone utvecklad inom Malmö högskola -
    som stöd i undervisningen.
  • Projekt Utvärdering av Webzone
  • Tove Blomgren och Lars Rauer, K3, har gjort en
    användarutvärdering av Webzone som helhet och
    tillsammans med studenter givit ett förslag till
    omstrukturering och utbyggnad av Webzone.
  • Projekt Tillgänglighet till sparade
    realtidsdiskussioner
  • Mandus Skön och Lars Rauer, K3, har arbetat med
    att utveckla en bevakning av nätbaserade
    diskussioner.
  • Om du anmäler deltagande till margareta.gisselberg
    _at_mah.se , garanteras fika!!
  • Kom ihåg att kolla på nämndens hemsida
    www.mah.se/nnu
  • - där vi informerar om vårt arbete, om aktuella
    konferenser etc.

26
?
Write a Comment
User Comments (0)
About PowerShow.com