Вы находитесь на странице: 1из 41

Exceptions

Error Handling

You do a lot on this in your practicals, so we'll just touch


on it here

The traditional way of handling errors is to return a value


that indicates success/failure/error

Probles!

"ould ignore the return value

Have to #eep chec#ing what the 'codes' are for


success, etc$

The result can't be returned in the usual way


public int divide%double a, double b& '
if %b(()& return *+, // error
double result ( a/b,
return ), // success
-
.
if % divide%x,y&/)& 0yste$out$println%12ailure334&,
Exceptions

5n exception is an object that can be thrown up by a


ethod when an error occurs and caught by the
calling code
public double divide%double a, double b& throws 6ivide7y8eroException '
if %b(()& throw 6ivide7y8eroException%&,
else return a/b
-
.
try '
double 9 ( divide%x,y&,
-
catch%6ivide7y8eroException d& '
// Handle error here
-
Exceptions

5dvantages!

"lass nae is descriptive %no need to loo# up codes&

6oesn't interrupt the natural flow of the code by


re:uiring constant tests

The exception object itself can contain state that


gives lots of detail on the error that caused the
exception

"an't be ignored, only handled


"opying ;ava <bjects
"loning

0oeties we really do want to copy an object

;ava calls this cloning

=e need special support for it


Person object
%nae (
17ob4&
r
Person object
%nae (
17ob4&
r
Person object
%nae (
17ob4&
r>copy
"loning

Every class in ;ava ultiately inherits fro the


Object class

The Object class contains a clone%& ethod

0o just call this to clone an object, right?

=rong3

0urprisingly, the proble is defining what copy


actually eans
"opying ;ava <bjects
"loning

0oeties we really do want to copy an object

;ava calls this cloning

=e need special support for it


Person object
%nae (
17ob4&
r
Person object
%nae (
17ob4&
r
Person object
%nae (
17ob4&
r>copy
"loning

Every class in ;ava ultiately inherits fro the


Object class

The Object class contains a clone%& ethod

0o just call this to clone an object, right?

=rong3

0urprisingly, the proble is defining what copy


actually eans
"loning
public class @y"lass '
private float price ( AA,
-
@y"lass
object
%price(AA&
"lone
@y"lass
object
%price(AA&
@y"lass
object
%price(AA&
0hallow and 6eep "opies
public class @y"lass '
private @y<ther"lass oc,
-
@y"lass
object
0
h
a
l
l
o
w
@y<ther"lass
object
@y"lass
object
@y<ther"lass
object
@y"lass
object
@y<ther"lass
object
@y"lass
object
@y"lass
object
@y<ther"lass
object
6
e
e
p
;ava "loning

0o do you want shallow or deep?

The default ipleentation of clone%& perfors a


shallow copy

7ut ;ava developers were worried that this ight not be


appropriate! they decided they wanted to #now for sure
that we'd thought about whether this was appropriate

;ava has a Cloneable interface

Bf you call clone on anything that doesn't extend this


interface, it fails
@ar#er Bnterfaces

Bf you go and loo# at what's in the "loneable interface,


you'll find it's epty33 =hat's going on?

=ell, the clone%& ethod is already inherited fro Object


so it doesn't need to specify it

This is an exaple of a Marker Interface

5 ar#er interface is an epty interface that is used to


label classes

This approach is found occasionally in the ;ava libraries


6istributing ;ava "lasses
6istributing "lasses

0o you've written soe great classes that ight be useful


to others$ You release the code$ =hat if you've naed your
class the sae as soeone else?

E$g$ There are probably +))s of 1Cector4 classes out


there$$3

@ost languages define soe way that you can #eep your
descriptive class nae without getting it confused with
others$

;ava uses packages$ 5 class belongs to a pac#age

5 naeless 'default' pac#age unless you specify


otherwise

You're supposed to choose a pac#age nae that is


uni:ue$

0un decided you should choose your doain nae

You do have your own doain nae, right? ,&


6istributing "lasses
pac#age u#$ca$ac$r#hDE,
iport u#$ca$ac$abcD+$F,
"lass =hatever '
.
-
"lass =hatever is part of this pac#age
Bport all the "lasses fro soe
other pac#age

You get to do lots ore about this in your practicals


5ccess @odifiers Gevisited

@ost Hanguages!

public I everyone can access directly

protected I only subclasses can access directly

private I nothing can access directly

;ava adds!

pac#age I anything in the sae pac#age can


access directly
The ;ava "lass Hibraries
;ava "lass Hibrary

;ava the platfor contains around J,)))


classes/interfaces

6ata 0tructures

Ketwor#ing, 2iles

Lraphical Mser Bnterfaces

0ecurity and Encryption

Bage Processing

@ultiedia authoring/playbac#

5nd ore$$$

5ll neatly%ish& arranged into pac#ages %see 5PB docs&


;ava's "ollections 2raewor#
<<interface>>
Collection
<<interface>>
Collection
<<interface>>
Collection
<<interface>>
Iterable

Bportant chun# of the class library

5 collection is soe sort of grouping of


things %objects&

Msually when we have soe grouping we


want to go through it %1iterate over it4&

The "ollections fraewor# has two ain


interfaces! Bterable and "ollections$ They
define a set of operations that all classes
in the "ollections fraewor# support

add%<bject o&, clear%&, isEpty%&, etc$


@ajor "ollections Bnterfaces

//interfaceNN 0et

Hi#e a atheatical set in 6@ +

5 collection of eleents with no duplicates

Carious concrete classes li#e Tree0et %which #eeps the set eleents sorted&

//interfaceNN Hist

5n ordered collection of eleents that ay contain duplicates

5rrayHist, Cector, Hin#edHist, etc$

//interfaceNN Oueue

5n ordered collection of eleents that ay contain duplicates and supports


reoval of eleents fro the head of the :ueue

PriorityOueue, Hin#edHBst, etc$


5
7
"
5
7
"
7
5
7
"
7
@ajor "ollections Bnterfaces

//interfaceNN @ap

Hi#e relations in 6@ +

@aps #ey objects to value objects

Peys ust be uni:ue

Calues can be duplicated and %soeties& null$


P+
5
7
7
PE PD
Lenerics

The original "ollections fraewor# just dealt with


collections of Objects

Everything in ;ava 1is*a4 Object so that way our


collections fraewor# will apply to any class we li#e
without any special odification$

Bt gets essy when we get soething fro our


collection though! it is returned as an Object and
we have to do a narrowing conversion to a#e use
of it!
// @a#e a Tree0et object
Tree0et ts ( new Tree0et%&,
// 5dd integers to it
ts$add%new Bnteger%E&&,
// Hoop through
iterator it ( ts$iterator%&,
while%it$hasKext%&& '
<bject o ( it$next%&,
Bnteger i ( %Bnteger&o,
-
Lenerics

Bt gets worse when you realise that the add%& ethod


doesn't stop us fro throwing in rando objects!
// @a#e a Tree0et object
Tree0et ts ( new Tree0et%&,
// 5dd integers to it
ts$add%new Bnteger%E&&,
ts$add%new Person%17ob4&&,
// Hoop through
iterator it ( ts$iterator%&,
while%it$hasKext%&& '
<bject o ( it$next%&,
Bnteger i ( %Bnteger&o,
-
Loing to fail for the
second eleent3
%7ut it will copile!
the error will be at
runtie&
Lenerics

To help solve this sort of proble, ;ava introduced


Generics in ;6P +$Q

7asically, this allows us to tell the copiler what is


supposed to go in the "ollection

0o it can generate an error at copile*tie, not run*


tie
// @a#e a Tree0et of Bntegers
Tree0et/BntegerN ts ( new Tree0et/BntegerN%&,
// 5dd integers to it
ts$add%new Bnteger%E&&,
ts$add%new Person%17ob4&&,
// Hoop through
iterator/BntegerN it ( ts$iterator%&,
while%it$hasKext%&& '
Bnteger i ( it$next%&,
-
=on't even copile
Ko need to cast !*&
Kotation in ;ava 5PB

0et/EN

Hist/EN

Oueue/EN

@ap/P,CN
Polyorphis Gevisited
You ight recognise Lenerics as the 1polyorphis4
you et in 2o"0 when using @H$
7oth allow you to write code that wor#s for ultiple
types
%Paraetric& Polyorphis R2PS or Lenerics R<<PS
The types are deterined at copile*tie
%0ub*type or ad*hoc& Polyorphis R<<PS
The types are deterined at run*tie
Keeds an inheritance tree
Lenerics and 0ubTyping
// <bject casting
Person p ( new Person%&,
5nial o ( %5nial& p,
// Hist casting
Hist/PersonN plist ( new Hin#edHist/PersonN%&,
Hist/5nialN alist ( %Hist/5nialN&plist,
<<interface>>
Collection
Person
<<interface>>
Collection
5nial
0o a list of Persons is a list of Animals, yes?
"oparing ;ava "lasses
"oparing Priitives
N Lreater Than
N( Lreater than or e:ual to
(( E:ual to
3( Kot e:ual to
/ Hess than
/( Hess than or e:ual to

"learly copare the value of a priitive

7ut what does %object+((objectD& ean??

0ae object?

0ae state %1value4& but different object?


<ption +! a((b, a3(b

These copare the references


Person p+ ( new Person%17ob4&,
Person pD ( new Person%17ob4&,
%p+((pD&,
%p+3(pD&,
p+((p+,
2alse %references differ&
True %references differ&
True %references the sae&
0tring s ( 1Hello4,
if %s((4Hello4& 0yste$out$println%1Hello4&,
else 0yste$out$println%1Kope4&,
<ption D! The e:uals%& @ethod

<bject defines an e:uals%& ethod$ 7y default, this


ethod just does the sae as (($

Geturns boolean, so can only test e:uality

<verride it if you want it to do soething different

@ost %all?& of the core ;ava classes have properly


ipleented e:uals%& ethods
Person p+ ( new Person%17ob4&,
Person pD ( new Person%17ob4&,
%p+((pD&,
0tring s+ ( 17ob4,
0tring sD ( 17ob4,
%s+((sD&,
2alse %we haven't
overridden the e:uals%&
ethod so it just
copares references
True %0tring has e:uals%&
overridden&
<ption E! "oparable/TN Bnterface
int copareTo%T obj&,

Part of the "ollections 2raewor#

Geturns an integer, r!

r/) This object is less than obj

r(() This object is e:ual to obj

rN) This object is greater than obj


<ption E! "oparable/TN Bnterface
public class Point ipleents "oparable/PointN '
private final int T,
private final int Y,
public Point %int, int y& ' T(x, Y(y, -
// sort by y, then x
public int copareTo%Point p& '
if % YNp$Y& return +,
else if %Y/p$Y& return *+,
else '
if %TNp$T& return +,
else if %T/p$T& return *+,
else return )$
-
-
-
// This will be sorted autoatically by y, then x
0et/PointN list ( new Tree0et/PointN%&,
<ption J! "oparator/TN interface
int copareTo%T obj+, T objD&

5lso part of the "ollections fraewor# and


allows us to specify a particular coparator
for a particular job

E$g$ a Person ight have a copareTo%&


ethod that sorts by surnae$ =e ight
wish to create a class 5ge"oparator that
sorts Person objects by age$ =e could then
feed that to a "ollections object$
0oe Exaples$$$
;ava's B/< fraewor#

0upport for syste input and output %fro/to sources


such as networ#, files, etc&$
<<interface>>
Collection
Reader
5bstract class for reading
data fro soe source
<<interface>>
Collection
Bnput0treaGeader
<<interface>>
Collection
2ileGeader
"oncrete Bnstance that wor#s
on an Bnput0trea object
0pecialisation that allows us to
specify a filenae, then creates
and Bnput0trea for it
0peeding it up

Bn general file B/< is sloowwww

<ne tric# we can use is that whenever we're as#ed to read


soe data in %say one byte& we actually read lots ore in
%say a #ilobyte& and buffer it soewhere on the assuption
that it will be wanted eventually and it will just be there in
eory, waiting for us$ !*&

;ava supports this in the for of a BufferedReader


2ileGeader f ( new 2ileGeader%&,
7ufferedGeader br ( new 7ufferedGeader%f&,
Reader
Bnput0treaGeader 7ufferedGeader
7ufferedGeader

=henever we call read%& on a


7ufferedGeader it loo#s in its
buffer to see whether it has
the data already

Bf not it passes the re:uest


onto the Geader object

=e'll coe bac# to this$$$


0peeding it up

Bn general file B/< is sloowwww

<ne tric# we can use is that whenever we're as#ed to read


soe data in %say one byte& we actually read lots ore in
%say a #ilobyte& and buffer it soewhere on the assuption
that it will be wanted eventually and it will just be there in
eory, waiting for us$ !*&

;ava supports this in the for of a BufferedReader


2ileGeader f ( new 2ileGeader%&,
7ufferedGeader br ( new 7ufferedGeader%f&,
Reader
Bnput0treaGeader 7ufferedGeader
7ufferedGeader

=henever we call read%& on a


7ufferedGeader it loo#s in its
buffer to see whether it has
the data already

Bf not it passes the re:uest


onto the Geader object

=e'll coe bac# to this$$$


0peeding it up

Bn general file B/< is sloowwww

<ne tric# we can use is that whenever we're as#ed to read


soe data in %say one byte& we actually read lots ore in
%say a #ilobyte& and buffer it soewhere on the assuption
that it will be wanted eventually and it will just be there in
eory, waiting for us$ !*&

;ava supports this in the for of a BufferedReader


2ileGeader f ( new 2ileGeader%&,
7ufferedGeader br ( new 7ufferedGeader%f&,
Reader
Bnput0treaGeader 7ufferedGeader
7ufferedGeader

=henever we call read%& on a


7ufferedGeader it loo#s in its
buffer to see whether it has
the data already

Bf not it passes the re:uest


onto the Geader object

=e'll coe bac# to this$$$

Вам также может понравиться