Professional Documents
Culture Documents
ndice
Lesson: Exceptions.....................................................................................................................9 What Is an Exception?....................................................................................................................9 The Catch or Specify Requirement...................................................................................................9 How to Throw Exceptions...............................................................................................................9 The try-with-resources Statement....................................................................................................9 nchec!e" Exceptions # The Contro$ersy.......................................................................................9 %"$anta&es of Exceptions...............................................................................................................9 Summary.......................................................................................................................................9 'uestions an" Exercises.................................................................................................................9 What Is an Exception?..............................................................................................................10 The Catch or Specify Re !ire"ent...........................................................................................11 The Three (in"s of Exceptions......................................................................................................)) *ypassin& Catch or Specify............................................................................................................)+ Catchin# and $and%in# Exceptions...........................................................................................1& The try '%oc(.............................................................................................................................1) The catch '%oc(s.......................................................................................................................1* Catchin& ,ore Than -ne Type of Exception with -ne Exception Han".er..........................................)/ The fina%%y '%oc(........................................................................................................................1+ The try,-ith,reso!rces State"ent...........................................................................................1. Suppresse" Exceptions.................................................................................................................)9 C.asses That Imp.ement the %utoC.osea0.e or C.osea0.e Interface...................................................)9 /!ttin# It 0%% To#ether..............................................................................................................19 Scenario )1 %n Exception -ccurs...................................................................................................+2 Scenario +1 The try *.oc! Exits 3orma..y........................................................................................+) Specifyin# the Exceptions Thro-n 1y a 2ethod......................................................................&) $o- to Thro- Exceptions.........................................................................................................&* The throw Statement....................................................................................................................+4 Throwa0.e C.ass an" Its Su0c.asses...............................................................................................+/ Error C.ass...................................................................................................................................+/ Exception C.ass............................................................................................................................+/ Chained Exceptions...................................................................................................................&. %ccessin& Stac! Trace Information.................................................................................................+5 6o&&in& %7I.................................................................................................................................+8 Creatin# Exception C%asses.......................................................................................................&3 %n Examp.e..................................................................................................................................+8 Choosin& a Superc.ass..................................................................................................................+9 4nchec(ed Exceptions 5 The Contro6ersy...............................................................................&7 0d6anta#es of Exceptions.........................................................................................................&9 %"$anta&e )1 Separatin& Error-Han".in& Co"e from :Re&u.ar: Co"e.................................................+9 %"$anta&e +1 7ropa&atin& Errors p the Ca.. Stac!.........................................................................;) %"$anta&e ;1 <roupin& an" =ifferentiatin& Error Types...................................................................;+ S!""ary...................................................................................................................................)) 8!estions and Exercises...........................................................................................................)* 'uestions.....................................................................................................................................;4 Exercises......................................................................................................................................;4
Lesson: Exceptions
The >a$a pro&rammin& .an&ua&e uses exceptions to han".e errors an" other exceptiona. e$ents. This .esson "escri0es when an" how to use exceptions.
What Is an Exception?
%n exception is an e$ent that occurs "urin& the execution of a pro&ram that "isrupts the norma. f.ow of instructions.
0d6anta#es of Exceptions
The use of exceptions to mana&e errors has some a"$anta&es o$er tra"itiona. error-mana&ement techniques. AouB.. .earn more in this section.
Excepciones >%C%
What Is an Exception?
The term exception is shorthan" for the phrase :exceptiona. e$ent.: 9efinition: %n exception is an e$ent? which occurs "urin& the execution of a pro&ram? that "isrupts the norma. f.ow of the pro&ramBs instructions.
When an error occurs within a metho"? the metho" creates an o0@ect an" han"s it off to the runtime system. The o0@ect? ca..e" an exception o0@ect? contains information a0out the error? inc.u"in& its type an" the state of the pro&ram when the error occurre". Creatin& an exception o0@ect an" han"in& it to the runtime system is ca..e" throwin& an exception. %fter a metho" throws an exception? the runtime system attempts to fin" somethin& to han".e it. The set of possi0.e :somethin&s: to han".e the exception is the or"ere" .ist of metho"s that ha" 0een ca..e" to &et to the metho" where the error occurre". The .ist of metho"s is !nown as the ca.. stac! Dsee the next fi&ureE. The runtime system searches the ca.. stac! for a metho" that contains a 0.oc! of co"e that can han".e the exception. This 0.oc! of co"e is ca..e" an exception han".er. The search 0e&ins with the metho" in which the error occurre" an" procee"s throu&h the ca.. stac! in the re$erse or"er in which the metho"s were ca..e". When an appropriate han".er is foun"? the runtime system passes the exception to the han".er. %n exception han".er is consi"ere" appropriate if the type of the exception o0@ect thrown matches the type that can 0e han".e" 0y the han".er. The exception han".er chosen is sai" to catch the exception. If the runtime system exhausti$e.y searches a.. the metho"s on the ca.. stac! without fin"in& an appropriate exception han".er? as shown in the next fi&ure? the runtime system Dan"? consequent.y? the pro&ramE terminates. Searchin& the ca.. stac! for the exception han".er.
What Is an Exception?
sin& exceptions to mana&e errors has some a"$anta&es o$er tra"itiona. error-mana&ement techniques. Aou can .earn more in the %"$anta&es of Exceptions section.
Excepciones >%C%
those in"icate" 0y RuntimeException an" its su0c.asses. Errors an" runtime exceptions are co..ecti$e.y !nown as unchec!e" exceptions.
The first .ine in 0o."face is a ca.. to a constructor. The constructor initia.iGes an output stream on a fi.e. If the fi.e cannot 0e opene"? the constructor throws an IOException. The secon" 0o."face .ine is a ca.. to the #rray"ist c.assBs $et metho"? which throws an IndexOutOf;oundsException if the $a.ue of its ar&ument is too sma.. D.ess than 2E or too .ar&e Dmore than the num0er of e.ements current.y containe" 0y the #rray"istE. If you try to compi.e the "istOfNumbers c.ass? the compi.er prints an error messa&e a0out the exception thrown 0y the File8riter constructor. Howe$er? it "oes not "isp.ay an error messa&e a0out the exception thrown 0y $et. The reason is that the exception thrown 0y the constructor? IOException? is a chec!e" exception? an" the one thrown 0y the $et metho"? IndexOutOf;oundsException? is an unchec!e" exception. 3ow that youBre fami.iar with the "istOfNumbers c.ass an" where the exceptions can 0e thrown within it? youBre rea"y to write exception han".ers to catch an" han".e those exceptions.
The se&ment in the examp.e .a0e.e" co"e contains one or more .e&a. .ines of co"e that cou." throw an exception. DThe catch an" finally 0.oc!s are exp.aine" in the next two su0sections.E To construct an exception han".er for the write"ist metho" from the "istOfNumbers c.ass? enc.ose the exception-throwin& statements of the write"ist metho" within a try 0.oc!. There is more than one way to "o this. Aou can put each .ine of co"e that mi&ht throw an exception within its own try 0.oc! an" pro$i"e separate exception han".ers for each. -r? you can put a.. the write"ist co"e within a sin&.e try 0.oc! an" associate mu.tip.e han".ers with it. The fo..owin& .istin& uses one try 0.oc! for the entire metho" 0ecause the co"e in question is $ery short.
private&"ist-Inte$er.&list+ private&static&final&int&/I0E&1&23+ Print8riter&out&1&null+ try&, &&&&/ystem.out.println49Entered&try&statement95+ &&&&out&1&new&Print8riter4new&File8riter49OutFile.txt955+ &&&&for&4int&i&1&3+&i&-&/I0E+&i665&, &&&&&&&&out.println49:alue&at'&9&6&i&6&9&1&9&6&list.$et4i55+ &&&&7 7 catch and finally statements . . .
If an exception occurs within the try 0.oc!? that exception is han".e" 0y an exception han".er associate" with it. To associate an exception han".er with a try 0.oc!? you must put a catch& 0.oc! after itI the next section? The catch *.oc!s? shows you how.
9
Excepciones >%C%
Each catch 0.oc! is an exception han".er an" han".es the type of exception in"icate" 0y its ar&ument. The ar&ument type? ExceptionType? "ec.ares the type of exception that the han".er can han".e an" must 0e the name of a c.ass that inherits from the Throwable c.ass. The han".er can refer to the exception with name. The catch 0.oc! contains co"e that is execute" if an" when the exception han".er is in$o!e". The runtime system in$o!es the exception han".er when the han".er is the first one in the ca.. stac! whose ExceptionType matches the type of the exception thrown. The system consi"ers it a match if the thrown o0@ect can .e&a..y 0e assi&ne" to the exception han".erBs ar&ument. The fo..owin& are two exception han".ers for the write"ist metho" # one for two types of chec!e" exceptions that can 0e thrown within the try statement1
try&, 7&catch&4FileNotFoundException&e5&, &&&&/ystem.err.println49FileNotFoundException'&9&6&e.$et<essa$e455+ &&&&throw&new&/ampleException4e5+ 7&catch&4IOException&e5&, &&&&/ystem.err.println49!au$ht&IOException'&9&6&e.$et<essa$e455+ 7
*oth han".ers print an error messa&e. The secon" han".er "oes nothin& e.se. *y catchin& any IOException thatBs not cau&ht 0y the first han".er? it a..ows the pro&ram to continue executin&. The first han".er? in a""ition to printin& a messa&e? throws a user-"efine" exception. DThrowin& exceptions is co$ere" in "etai. .ater in this chapter in the How to Throw Exceptions section.E In this examp.e? when the FileNotFoundException is cau&ht it causes a user-"efine" exception ca..e" /ampleException to 0e thrown. Aou mi&ht want to "o this if you want your pro&ram to han".e an exception in this situation in a specific way. Exception han".ers can "o more than @ust print error messa&es or ha.t the pro&ram. They can "o error reco$ery? prompt the user to ma!e a "ecision? or propa&ate the error up to a hi&her-.e$e. han".er usin& chaine" exceptions? as "escri0e" in the Chaine" Exceptions section.
Catchin# 2ore Than ;ne Type of Exception -ith ;ne Exception $and%er
In >a$a SE 8 an" .ater? a sin&.e catch 0.oc! can han".e more than one type of exception. This
)2
feature can re"uce co"e "up.ication an" .essen the temptation to catch an o$er.y 0roa" exception. In the catch c.ause? specify the types of exceptions that 0.oc! can han".e? an" separate each exception type with a $ertica. 0ar D =E1
catch&4IOException=/>"Exception&ex5&, &&&&lo$$er.lo$4ex5+ &&&&throw&ex+ 7
<ote1 If a catch 0.oc! han".es more than one exception type? then the catch parameter is imp.icit.y final. In this examp.e? the catch parameter ex is final an" therefore you cannot assi&n any $a.ues to it within the catch 0.oc!.
<ote: If the >C, exits whi.e the try or catch co"e is 0ein& execute"? then the finally 0.oc! may not execute. 6i!ewise? if the threa" executin& the try or catch co"e is interrupte" or !i..e"? the finally 0.oc! may not execute e$en thou&h the app.ication as a who.e continues. The try 0.oc! of the write"ist metho" that youB$e 0een wor!in& with here opens a Print8riter. The pro&ram shou." c.ose that stream 0efore exitin& the write"ist metho". This poses a somewhat comp.icate" pro0.em 0ecause write"istBs try 0.oc! can exit in one of three ways. ). The new&File8riter statement fai.s an" throws an IOException. +. The vector.element#t4i5 statement fai.s an" #rrayIndexOutOf;oundsException. ;. E$erythin& succee"s an" the try 0.oc! exits norma..y. throws an
The runtime system a.ways executes the statements within the finally 0.oc! re&ar".ess of what happens within the try 0.oc!. So itBs the perfect p.ace to perform c.eanup. The fo..owin& finally 0.oc! for the write"ist metho" c.eans up an" then c.oses the Print8riter.
finally&, &&&&if&4out&)1&null5&,& &&&&&&&&/ystem.out.println49!losin$&Print8riter95+ &&&&&&&&out.close45+& &&&&7&else&,& &&&&&&&&/ystem.out.println49Print8riter¬&open95+ &&&&7& 7&
))
Excepciones >%C%
In the write"ist examp.e? you cou." pro$i"e for c.eanup without the inter$ention of a finally& 0.oc!. For examp.e? you cou." put the co"e to c.ose the Print8riter at the en" of the try& 0.oc! an" a&ain within the exception han".er for #rrayIndexOutOf;oundsException? as fo..ows.
try&, &&&& &&&&%%&Don't do this; it duplicates code.& &&&&out.close(); &&&& 7&catch&4FileNotFoundException&e5&, &&&&%%&Don't do this; it duplicates code. &&&&out.close(); &&&&/ystem.err.println49!au$ht&FileNotFoundException'&9&6&e.$et<essa$e455+ &&&&throw&new&RuntimeException4e5+ &&&& 7&catch&4IOException&e5&, &&&&/ystem.err.println49!au$ht&IOException'&9&6&e.$et<essa$e455+ 7
Howe$er? this "up.icates co"e? thus ma!in& the co"e "ifficu.t to rea" an" error-prone shou." you mo"ify it .ater. For examp.e? if you a"" co"e that can throw a new type of exception to the try& 0.oc!? you ha$e to remem0er to c.ose the Print8riter within the new exception han".er.
I"portant: The finally 0.oc! is a !ey too. for pre$entin& resource .ea!s. When c.osin& a fi.e or otherwise reco$erin& resources? p.ace the co"e in a finally 0.oc! to ensure that resource is a.ways reco$ere". If you are usin& >a$a SE 8 or .ater? consi"er usin& the try with-resources statement in these situations? which automatica..y re.eases system resources when no .on&er nee"e". The next section has more information.
)+
In this examp.e? the resource "ec.are" in the try-with-resources statement is a ;ufferedReader. The "ec.aration statement appears within parentheses imme"iate.y after the try !eywor". The c.ass ;ufferedReader? in >a$a SE 8 an" .ater? imp.ements the interface java.lan$.#uto!loseable. *ecause the ;ufferedReader instance is "ec.are" in a trywith-resource statement? it wi.. 0e c.ose" re&ar".ess of whether the try statement comp.etes norma..y or a0rupt.y Das a resu.t of the metho" ;ufferedReader.read"ine throwin& an IOExceptionE. 7rior to >a$a SE 8? you can use a finally 0.oc! to ensure that a resource is c.ose" re&ar".ess of whether the try statement comp.etes norma..y or a0rupt.y. The fo..owin& examp.e uses a finally 0.oc! instea" of a try-with-resources statement1
static&/trin$&readFirst"ineFromFile8ithFinally;loc?4/trin$&path5 &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&throws&IOException&, &&&&;ufferedReader&br&1&new&;ufferedReader4new&FileReader4path55+ &&&&try&, &&&&&&&&return&br.read"ine45+ &&&&7&finally&, &&&&&&&&if&4br&)1&null5&br.close45+ &&&&7 7
Howe$er? in this examp.e? if the metho"s read"ine an" close 0oth throw exceptions? then the metho" readFirst"ineFromFile8ithFinally;loc? throws the exception thrown from the finally 0.oc!I the exception thrown from the try 0.oc! is suppresse". In contrast? in the examp.e readFirst"ineFromFile? if exceptions are thrown from 0oth the try 0.oc! an" the try-with-resources statement? then the metho" readFirst"ineFromFile throws the exception thrown from the try 0.oc!I the exception thrown from the try-with-resources 0.oc! is suppresse". In >a$a SE 8 an" .ater? you can retrie$e suppresse" exceptionsI see the section Suppresse" Exceptions for more information. Aou may "ec.are one or more resources in a try-with-resources statement. The fo..owin& examp.e retrie$es the names of the fi.es pac!a&e" in the Gip fi.e @ipFileName an" creates a text fi.e that
);
Excepciones >%C%
In this examp.e? the try-with-resources statement contains two "ec.arations that are separate" 0y a semico.on1 0ipFile an" ;uffered8riter. When the 0.oc! of co"e that "irect.y fo..ows it terminates? either norma..y or 0ecause of an exception? the close metho"s of the ;uffered8riter an" 0ipFile o0@ects are automatica..y ca..e" in this or"er. 3ote that the close metho"s of resources are ca..e" in the opposite or"er of their creation. The fo..owin& examp.e uses a try-with-resources statement to automatica..y c.ose a java.sEl./tatement o0@ect1
public&static&void&viewTable4!onnection&con5&throws&/>"Exception&, &&&&/trin$&Euery&1&9select&!OFCN#<EA&/BPCIFA&PRI!EA&/#"E/A&TOT#"&from&!OFFEE/9+ &&&&try (+tate(ent st(t " con.create+tate(ent())&, &&&&&&&&Result/et&rs&1&stmt.execute>uery4Euery5+ &&&&&&&&while&4rs.next455&, &&&&&&&&&&&&/trin$&coffeeName&1&rs.$et/trin$49!OFCN#<E95+ &&&&&&&&&&&&int&supplierIF&1&rs.$etInt49/BPCIF95+ &&&&&&&&&&&&float&price&1&rs.$etFloat49PRI!E95+ &&&&&&&&&&&&int&sales&1&rs.$etInt49/#"E/95+ &&&&&&&&&&&&int&total&1&rs.$etInt49TOT#"95+ &&&&&&&&&&&&/ystem.out.println4coffeeName&6&9A&9&6&supplierIF&6&9A&9&6& &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&price&6&9A&9&6&sales&6&9A&9&6&total5+ )4
The resource java.sEl./tatement use" in this examp.e is part of the >=*C 4.) an" .ater %7I. <ote1 % try-with-resources statement can ha$e catch an" finally 0.oc!s @ust .i!e an or"inary try statement. In a try-with-resources statement? any catch or finally 0.oc! is run after the resources "ec.are" ha$e 0een c.ose".
S!ppressed Exceptions
%n exception can 0e thrown from the 0.oc! of co"e associate" with the try-with-resources statement. In the examp.e writeToFile0ipFile!ontents? an exception can 0e thrown from the try 0.oc!? an" up to two exceptions can 0e thrown from the try-with-resources statement when it tries to c.ose the 0ipFile an" ;uffered8riter o0@ects. If an exception is thrown from the try 0.oc! an" one or more exceptions are thrown from the try-with-resources statement? then those exceptions thrown from the try-with-resources statement are suppresse"? an" the exception thrown 0y the 0.oc! is the one that is thrown 0y the writeToFile0ipFile!ontents& metho". Aou can retrie$e these suppresse" exceptions 0y ca..in& the Throwable.$et/uppressed metho" from the exception thrown 0y the try 0.oc!.
)/
Excepciones >%C%
%s mentione" pre$ious.y? this metho"Bs try 0.oc! has three "ifferent exit possi0i.itiesI here are two of them. ). Co"e in the try statement fai.s an" throws an exception. This cou." 0e an IOException& cause" 0y the new&File8riter statement or an #rrayIndexOutOf;oundsException& cause" 0y a wron& in"ex $a.ue in the for .oop. +. E$erythin& succee"s an" the try statement exits norma..y. 6etBs .oo! at what happens in the write"ist metho" "urin& these two exit possi0i.ities.
searchin& at the top of the metho" ca.. stac! for an appropriate exception han".er. In this examp.e? when the IOException occurs? the File8riter constructor is at the top of the ca.. stac!. Howe$er? the File8riter constructor "oesnBt ha$e an appropriate exception han".er? so the runtime system chec!s the next metho" # the write"ist metho" # in the metho" ca.. stac!. The write"ist metho" has two exception han".ers1 one for IOException an" one for #rrayIndexOutOf;oundsException. The runtime system chec!s write"istBs han".ers in the or"er in which they appear after the try& statement. The ar&ument to the first exception han".er is #rrayIndexOutOf;oundsException. This "oes not match the type of exception thrown? so the runtime system chec!s the next exception han".er # IOException. This matches the type of exception that was thrown? so the runtime system en"s its search for an appropriate exception han".er. 3ow that the runtime has foun" an appropriate han".er? the co"e in that catch 0.oc! is execute". %fter the exception han".er executes? the runtime system passes contro. to the finally 0.oc!. Co"e in the finally 0.oc! executes re&ar".ess of the exception cau&ht a0o$e it. In this scenario? the File8riter was ne$er opene" an" "oesnBt nee" to 0e c.ose". %fter the finally 0.oc! finishes executin&? the pro&ram continues with the first statement after the finally 0.oc!. HereBs the comp.ete output from the "istOfNumbers pro&ram that appears when an IOException is thrown.
Enterin$&try&statement !au$ht&IOException'&OutFile.txt Print8riter¬&open&
The 0o."face co"e in the fo..owin& .istin& shows the statements that &et execute" "urin& this scenario1
public&void&write"ist45&, &&&)rintWriter out " null; &&&&try , &&&&&&&&+yste(.out.println("-ntering try state(ent"); &&&&&&&&out " new )rintWriter(new FileWriter("OutFile.txt")); &&&&&&&&for&4int&i&1&3+&i&-&/I0E+&i665 &&&&&&&&&&&&out.println49:alue&at'&9&6&i&6&9&1&9&6&vector.element#t4i55+ &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&7&catch&4#rrayIndexOutOf;oundsException&e5&, &&&&&&&&/ystem.err.println49!au$ht&#rrayIndexOutOf;oundsException'&9 &&&&&&&&&&&&&&&&&&&&&&&&&&&6&e.$et<essa$e455+ &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&7&catch (.O-xception e) , &&&&&&&&+yste(.err.println("/aught .O-xception0 " 1 e.get2essage()); &&&&3 finally , &&&&&&&&if (out 4" null) , &&&&&&&&&&&&/ystem.out.println49!losin$&Print8riter95+ &&&&&&&&&&&&out.close45+ &&&&&&&&7& &&&&&&&&else , &&&&&&&&&&&&+yste(.out.println(")rintWriter not open"); &&&&&&&&3 &&&&7 7
)8
Excepciones >%C%
The 0o."face co"e in the fo..owin& samp.e shows the statements that &et execute" "urin& this scenario.
public&void&write"ist45&, &&&&)rintWriter out " null; &&&&try , &&&&&&&&+yste(.out.println("-ntering try state(ent"); &&&&&&&&out " new )rintWriter(new FileWriter("OutFile.txt")); &&&&&&&&for (int i " 5; i 6 +.&-; i11) &&&&&&&&&&&&out.println("7alue at0 " 1 i 1 " " " 1 $ector.ele(ent8t(i)); &&&&&&&&&&&&&&&&&& &&&&3&catch&4#rrayIndexOutOf;oundsException&e5&, &&&&&&&&/ystem.err.println49!au$ht&#rrayIndexOutOf;oundsException'&9 &&&&&&&&&&&&&&&&&&&&&&&&&&&6&e.$et<essa$e455+ &&&&7&catch&4IOException&e5&, &&&&&&&&/ystem.err.println49!au$ht&IOException'&9&6&e.$et<essa$e455+ &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&7&finally , &&&&&&&&if (out 4" null) , &&&&&&&&&&&&+yste(.out.println("/losing )rintWriter"); &&&&&&&&&&&&out.close(); &&&&&&&&3& &&&&&&&&else&, &&&&&&&&&&&&/ystem.out.println49Print8riter¬&open95+ &&&&&&&&7 &&&&7 7
)9
To specify that write"ist can throw two exceptions? a"" a throws c.ause to the metho" "ec.aration for the write"ist metho". The throws c.ause comprises the throws !eywor" fo..owe" 0y a comma-separate" .ist of a.. the exceptions thrown 0y that metho". The c.ause &oes after the metho" name an" ar&ument .ist an" 0efore the 0race that "efines the scope of the metho"I hereBs an examp.e.
public&void&write"ist45&throws .O-xception* 8rray.ndexOutOfBounds-xception&,
Remem0er that #rrayIndexOutOf;oundsException is an unchec!e" exceptionI inc.u"in& it in the throws c.ause is not man"atory. Aou cou." @ust write the fo..owin&.
public&void&write"ist45&throws .O-xception&,
)9
Excepciones >%C%
6etBs .oo! at the throw statement in context. The fo..owin& pop metho" is ta!en from a c.ass that imp.ements a common stac! o0@ect. The metho" remo$es the top e.ement from the stac! an" returns the o0@ect.
public&Object&pop45&, &&&&Object&obj+ &&&&if&4si@e&11&35&, &&&&&&&&throw new -(pty+tac9-xception(); &&&&7 &&&&obj&1&object#t4si@e& &25+ &&&&setObject#t4si@e& &2A&null5+ &&&&si@e + &&&&return&obj+ 7
The pop metho" chec!s to see whether any e.ements are on the stac!. If the stac! is empty Dits siGe is equa. to 3E? pop instantiates a new Empty/tac?Exception o0@ect Da mem0er of java.utilE an" throws it. The Creatin& Exception C.asses section in this chapter exp.ains how to create your own exception c.asses. For now? a.. you nee" to remem0er is that you can throw on.y o0@ects that inherit from the java.lan$.Throwable c.ass. 3ote that the "ec.aration of the pop metho" "oes not contain a throws c.ause. Empty/tac?Exception is not a chec!e" exception? so pop is not require" to state that it mi&ht occur.
+2
Error C%ass
When a "ynamic .in!in& fai.ure or other har" fai.ure in the >a$a $irtua. machine occurs? the $irtua. machine throws an Error. Simp.e pro&rams typica..y "o not catch or throw Errors.
Exception C%ass
,ost pro&rams throw an" catch o0@ects that "eri$e from the Exception c.ass. %n Exception in"icates that a pro0.em occurre"? 0ut it is not a serious system pro0.em. ,ost pro&rams you write wi.. throw an" catch Exceptions as oppose" to Errors. The >a$a p.atform "efines the many "escen"ants of the Exception c.ass. These "escen"ants in"icate $arious types of exceptions that can occur. For examp.e? Ille$al#ccessException& si&na.s that a particu.ar metho" cou." not 0e foun"? an" Ne$ative#rray/i@eException& in"icates that a pro&ram attempte" to create an array with a ne&ati$e siGe. -ne Exception su0c.ass? RuntimeException? is reser$e" for exceptions that in"icate incorrect use of an %7I. %n examp.e of a runtime exception is NullPointerException? which occurs when a metho" tries to access a mem0er of an o0@ect throu&h a null reference. The section nchec!e" Exceptions # The Contro$ersy "iscusses why most app.ications shou."nBt throw runtime exceptions or su0c.ass RuntimeException.
+)
Excepciones >%C%
Chained Exceptions
%n app.ication often respon"s to an exception 0y throwin& another exception. In effect? the first exception causes the secon" exception. It can 0e $ery he.pfu. to !now when one exception causes another. Chaine" Exceptions he.p the pro&rammer "o this. The fo..owin& are the metho"s an" constructors in Throwable that support chaine" exceptions.
Throwable&$et!ause45 Throwable&init!ause4Throwable5 Throwable4/trin$A&Throwable5 Throwable4Throwable5
The Throwable ar&ument to init!ause an" the Throwable constructors is the exception that cause" the current exception. $et!ause returns the exception that cause" the current exception? an" init!ause sets the current exceptionBs cause. The fo..owin& examp.e shows how to use a chaine" exception.
try&, 7&catch&4IOException&e5&, &&&&throw&new&/ampleException49Other&IOException9A&e5+ 7
In this examp.e? when an IOException is cau&ht? a new /ampleException exception is create" with the ori&ina. cause attache" an" the chain of exceptions is thrown up to the next hi&her .e$e. exception han".er.
9efinition: % stac! trace pro$i"es information on the execution history of the current threa" an" .ists the names of the c.asses an" metho"s that were ca..e" at the point when the exception occurre". % stac! trace is a usefu. "e0u&&in& too. that youB.. norma..y ta!e a"$anta&e of when an exception has 0een thrown. The fo..owin& co"e shows how to ca.. the $et/tac?Trace metho" on the exception o0@ect.
catch&4Exception&cause5&, &&&&/tac?TraceElement&elementsHI&1&cause.$et/tac?Trace45+ &&&&for&4int&i&1&3A&n&1&elements.len$th+&i&-&n+&i665&,&&&&&&& &&&&&&&&/ystem.err.println4elementsHiI.$etFileName45 &&&&&&&&&&&&6&9'9&6&elementsHiI.$et"ineNumber45& &&&&&&&&&&&&6&9..&9 &&&&&&&&&&&&6&elementsHiI.$et<ethodName45&6&94595+ &&&&7 7
++
Chaine" Exceptions
Lo##in# 0/I
The next co"e snippet .o&s where an exception occurre" from within the catch 0.oc!. Howe$er? rather than manua..y parsin& the stac! trace an" sen"in& the output to /ystem.err45? it sen"s the output to a fi.e usin& the .o&&in& faci.ity in the java.util.lo$$in$ pac!a&e.
try&, &&&&Jandler&handler&1&new&FileJandler49OutFile.lo$95+ &&&&"o$$er.$et"o$$er4995.addJandler4handler5+ &&&& 7&catch&4IOException&e5&, &&&&"o$$er&lo$$er&1&"o$$er.$et"o$$er49package.name95+& &&&&/tac?TraceElement&elementsHI&1&e.$et/tac?Trace45+ &&&&for&4int&i&1&3A&n&1&elements.len$th+&i&-&n+&i665&, &&&&&&&&lo$$er.lo$4"evel.8#RNINDA&elementsHiI.$et<ethodName455+ &&&&7 7
+;
Excepciones >%C%
0n Exa"p%e
Suppose you are writin& a .in!e" .ist c.ass. The c.ass supports the fo..owin& metho"s? amon& others1 o!#ect8t(int n) # Returns the o0@ect in the nth position in the .ist. Throws an exception if the ar&ument is .ess than 2 or more than the num0er of o0@ects current.y in the .ist. firstO!#ect() # Returns the first o0@ect in the .ist. Throws an exception if the .ist contains no o0@ects. indexOf(O!#ect o) # Searches the .ist for the specifie" Object an" returns its position in the .ist. Throws an exception if the o0@ect passe" into the metho" is not in the .ist. The .in!e" .ist c.ass can throw mu.tip.e exceptions? an" it wou." 0e con$enient to 0e a0.e to catch a.. exceptions thrown 0y the .in!e" .ist with one exception han".er. %.so? if you p.an to "istri0ute your .in!e" .ist in a pac!a&e? a.. re.ate" co"e shou." 0e pac!a&e" toðer. Thus? the .in!e" .ist shou." pro$i"e its own set of exception c.asses. The next fi&ure i..ustrates one possi0.e c.ass hierarchy for the exceptions thrown 0y the .in!e" .ist.
Choosin# a S!perc%ass
%ny Exception su0c.ass can 0e use" as the parent c.ass of "in?ed"istException. Howe$er? a quic! perusa. of those su0c.asses shows that they are inappropriate 0ecause they are either too specia.iGe" or comp.ete.y unre.ate" to "in?ed"istException. Therefore? the parent c.ass of "in?ed"istException& shou." 0e Exception. ,ost app.ets an" app.ications you write wi.. throw o0@ects that are Exceptions. Errors are norma..y use" for serious? har" errors in the system? such as those that pre$ent the >C, from runnin&.
+4
<ote: For rea"a0.e co"e? itBs &oo" practice to appen" the strin& Exception to the names of a.. c.asses that inherit D"irect.y or in"irect.yE from the Exception c.ass.
+/
Excepciones >%C%
0d6anta#es of Exceptions
3ow that you !now what exceptions are an" how to use them? itBs time to .earn the a"$anta&es of usin& exceptions in your pro&rams.
%t first &.ance? this function seems simp.e enou&h? 0ut it i&nores a.. the fo..owin& potentia. errors. What What What What What happens happens happens happens happens if if if if if the fi.e canBt 0e opene"? the .en&th of the fi.e canBt 0e "etermine"? enou&h memory canBt 0e a..ocate"? the rea" fai.s? the fi.e canBt 0e c.ose"?
To han".e such cases? the readFile function must ha$e more co"e to "o error "etection? reportin&? an" han".in&. Here is an examp.e of what the function mi&ht .oo! .i!e.
error!odeType&readFile , &&&&initiali@e&error!ode&1&3+ &&&& &&&&open the file; &&&&if&4theFileIsOpen5&, &&&&&&&&determine the length of the file; &&&&&&&&if&4gotTheFileLength5&, &&&&&&&&&&&&allocate that much memory; &&&&&&&&&&&&if&4gotEnough emory5&, &&&&&&&&&&&&&&&&read the file into memory; &&&&&&&&&&&&&&&&if&4readFailed5&, &&&&&&&&&&&&&&&&&&&&error!ode&1& 2+ &&&&&&&&&&&&&&&&7 &&&&&&&&&&&&7&else&, &&&&&&&&&&&&&&&&error!ode&1& K+ &&&&&&&&&&&&7 &&&&&&&&7&else&, &&&&&&&&&&&&error!ode&1& L+ &&&&&&&&7 &&&&&&&&close the file; &&&&&&&&if&4theFile!idnt"lose&MM&error"ode&11&35&, &&&&&&&&&&&&error!ode&1& N+ &&&&&&&&7&else&, &&&&&&&&&&&&error!ode&1&error!ode&and& N+ +5
%"$anta&es of Exceptions
&&&&&&&&7 &&&&7&else&, &&&&&&&&error!ode&1& O+ &&&&7 &&&&return&error!ode+ 7
ThereBs so much error "etection? reportin&? an" returnin& here that the ori&ina. se$en .ines of co"e are .ost in the c.utter. Worse yet? the .o&ica. f.ow of the co"e has a.so 0een .ost? thus ma!in& it "ifficu.t to te.. whether the co"e is "oin& the ri&ht thin&1 Is the fi.e rea..y 0ein& c.ose" if the function fai.s to a..ocate enou&h memory? ItBs e$en more "ifficu.t to ensure that the co"e continues to "o the ri&ht thin& when you mo"ify the metho" three months after writin& it. ,any pro&rammers so.$e this pro0.em 0y simp.y i&norin& it # errors are reporte" when their pro&rams crash. Exceptions ena0.e you to write the main f.ow of your co"e an" to "ea. with the exceptiona. cases e.sewhere. If the readFile function use" exceptions instea" of tra"itiona. error-mana&ement techniques? it wou." .oo! more .i!e the fo..owin&.
readFile&, &&&&try&, &&&&&&&&open the file; determine its size; allocate that much memory; read the file into memory; close the file; &&&&7&catch&4fileOpenFailed5&, &&&&&&&doSomething; &&&&7&catch&4si#e!eterminationFailed5&, &&&&&&&&doSomething; &&&&7&catch&4memory$llocationFailed5&, &&&&&&&&doSomething; &&&&7&catch&4readFailed5&, &&&&&&&&doSomething; &&&&7&catch&4file"loseFailed5&, &&&&&&&&doSomething; &&&&7 7
3ote that exceptions "onBt spare you the effort of "oin& the wor! of "etectin&? reportin&? an" han".in& errors? 0ut they "o he.p you or&aniGe the wor! more effecti$e.y.
Excepciones >%C%
Suppose a.so that method2 is the on.y metho" intereste" in the errors that mi&ht occur within readFile. Tra"itiona. error-notification techniques force methodK an" methodL to propa&ate the error co"es returne" 0y readFile up the ca.. stac! unti. the error co"es fina..y reach method2#the on.y metho" that is intereste" in them.
(ethod:&, &&&&error!odeType&error+ &&&&error&1&call method2; &&&&if&4error5 &&&&&&&&doErrorProcessing; &&&&else &&&&&&&&proceed; 3 error!odeType&(ethod; , &&&&error!odeType&error+ &&&&error&1&call&(ethod<; &&&&if&4error5 &&&&&&&&return&error+ &&&&else &&&&&&&&proceed; 3 error!odeType&(ethod< , &&&&error!odeType&error+ &&&&error&1&call readFile; &&&&if&4error5 &&&&&&&&return&error+ &&&&else &&&&&&&&proceed; 3
Reca.. that the >a$a runtime en$ironment searches 0ac!war" throu&h the ca.. stac! to fin" any metho"s that are intereste" in han".in& a particu.ar exception. % metho" can "uc! any exceptions thrown within it? there0y a..owin& a metho" farther up the ca.. stac! to catch it. Hence? on.y the metho"s that care a0out errors ha$e to worry a0out "etectin& errors.
(ethod:&, &&&&try&, &&&&&&&&call method2; &&&&7&catch&4exception&e5&, &&&&&&&&doErrorProcessing; &&&&7 7 (ethod;&throws&exception&, &&&&call method3; 7 (ethod<&throws&exception&, &&&&call readFile; 3 +9
%"$anta&es of Exceptions
Howe$er? as the pseu"oco"e shows? "uc!in& an exception requires some effort on the part of the mi"".eman metho"s. %ny chec!e" exceptions that can 0e thrown within a metho" must 0e specifie" in its throws c.ause.
% metho" can catch an exception 0ase" on its &roup or &enera. type 0y specifyin& any of the exceptionBs superc.asses in the catch statement. For examp.e? to catch a.. IH- exceptions? re&ar".ess of their specific type? an exception han".er specifies an IOException ar&ument.
catch&4IOException&e5&, &&&&... 7
This han".er wi.. 0e a0.e to catch a.. IH- exceptions? inc.u"in& FileNotFoundException? EOFException? an" so on. Aou can fin" "etai.s a0out what occurre" 0y queryin& the ar&ument passe" to the exception han".er. For examp.e? use the fo..owin& to print the stac! trace.
catch&4IOException&e5&, &&&&%%&Output&$oes&to&/ystem.err. &&&&e.print/tac?Trace45+ &&&&%%&/end&trace&to&stdout. &&&&e.print/tac?Trace4/ystem.out5+ 7
Aou cou." e$en set up an exception han".er that han".es any Exception with the han".er here.
%%&$ %too& general exception handler catch&4Exception&e5&, &&&&... 7
The Exception c.ass is c.ose to the top of the Throwable c.ass hierarchy. Therefore? this han".er wi.. catch many other exceptions in a""ition to those that the han".er is inten"e" to catch. Aou may want to han".e exceptions this way if a.. you want your pro&ram to "o? for examp.e? is print out an error messa&e for the user an" then exit. In most situations? howe$er? you want exception han".ers to 0e as specific as possi0.e. The reason is that the first thin& a han".er must "o is "etermine what type of exception occurre" 0efore it can "eci"e on the 0est reco$ery strate&y. In effect? 0y not catchin& specific errors? the han".er must
+9
Excepciones >%C%
accommo"ate any possi0i.ity. Exception han".ers that are too &enera. can ma!e co"e more errorprone 0y catchin& an" han".in& exceptions that werenBt anticipate" 0y the pro&rammer an" for which the han".er was not inten"e". %s note"? you can create &roups of exceptions an" han".e exceptions in a &enera. fashion? or you can use the specific exception type to "ifferentiate exceptions an" han".e exceptions in an exact fashion.
S!""ary
% pro&ram can use exceptions to in"icate that an error occurre". To throw an exception? use the throw statement an" pro$i"e it with an exception o0@ect # a "escen"ant of Throwable # to pro$i"e information a0out the specific error that occurre". % metho" that throws an uncau&ht? chec!e" exception must inc.u"e a throws c.ause in its "ec.aration. % pro&ram can catch exceptions 0y usin& a com0ination of the try? catch? an" finally 0.oc!s. The try 0.oc! i"entifies a 0.oc! of co"e in which an exception can occur. The catch 0.oc! i"entifies a 0.oc! of co"e? !nown as an exception han".er? that can han".e a particu.ar type of exception. The finally 0.oc! i"entifies a 0.oc! of co"e that is &uarantee" to execute? an" is the ri&ht p.ace to c.ose fi.es? reco$er resources? an" otherwise c.ean up after the co"e enc.ose" in the try 0.oc!. The try statement shou." contain at .east one catch 0.oc! or a finally 0.oc! an" may ha$e mu.tip.e catch 0.oc!s. The c.ass of the exception o0@ect in"icates the type of exception thrown. The exception o0@ect can contain further information a0out the error? inc.u"in& an error messa&e. With exception chainin&? an exception can point to the exception that cause" it? which can in turn point to the exception that cause" it? an" so on.
;2
What is wron& with usin& this type of exception han".er? ;. Is there anythin& wron& with the fo..owin& exception han".er as written? Wi.. this co"e compi.e?
try&, 7&catch&4Exception&e5&, &&&& 7&catch&4#rithmeticException&a5&, &&&& 7
4. ,atch each situation in the first .ist with an item in the secon" .ist. a. intHI & #+ #H3I&1&3+ 0. The >C, starts runnin& your pro&ram? 0ut the >C, canBt fin" the >a$a p.atform c.asses. DThe >a$a p.atform c.asses resi"e in classes.@ip or rt.jar.E c. % pro&ram is rea"in& a stream an" reaches the end&of&stream mar!er. ". *efore c.osin& the stream an" after reachin& the end & of & stream mar!er? a pro&ram tries to rea" the stream a&ain. e. JJerror f. JJchec!e" exception &. JJcompi.e error h. JJno exception
Exercises
i. %"" a read"ist metho" to "istOfNumbers.java. This metho" shou." rea" in int $a.ues from a fi.e? print each $a.ue? an" appen" them to the en" of the $ector. Aou shou." catch a.. appropriate errors. Aou wi.. a.so nee" a text fi.e containin& num0ers to rea" in. @. ,o"ify the fo..owin& cat metho" so that it wi.. compi.e.
public&static&void&cat4File&file5&, &&&&Random#ccessFile&input&1&null+ &&&&/trin$&line&1&null+ &&&&try&, &&&&&&&&input&1&new&Random#ccessFile4fileA&9r95+ &&&&&&&&while&44line&1&input.read"ine455&)1&null5&, &&&&&&&&&&&&/ystem.out.println4line5+ &&&&&&&&7 &&&&&&&&return+ &&&&7&finally&, &&&&&&&&if&4input&)1&null5&, &&&&&&&&&&&&input.close45+ &&&&&&&&7 &&&&7 7
;)