You are on page 1of 31

Excepciones en Java

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.

The Catch or Specify Re !ire"ent


This section co$ers how to catch an" han".e exceptions. The "iscussion inc.u"es the try? catch? an" finally 0.oc!s? as we.. as chaine" exceptions an" .o&&in&.

$o- to Thro- Exceptions


This section co$ers the throw statement an" the Throwable c.ass an" its su0c.asses.

The try,-ith,reso!rces State"ent


This section "escri0es the try-with-resources statement? which is a try statement that "ec.ares one or more resources. % resource is as an o0@ect that must 0e c.ose" after the pro&ram is finishe" with it. The try-with-resources statement ensures that each resource is c.ose" at the en" of the statement.

4nchec(ed Exceptions 5 The Contro6ersy


This section exp.ains the correct an" incorrect use of the unchec!e" exceptions in"icate" 0y su0c.asses of RuntimeException.

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.

S!""ary 8!estions and Exercises

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.

The Catch or Specify Re !ire"ent


Ca.i" >a$a pro&rammin& .an&ua&e co"e must honor the Catch or Specify Requirement. This means that co"e that mi&ht throw certain exceptions must 0e enc.ose" 0y either of the fo..owin&1 % try statement that catches the exception. The try must pro$i"e a han".er for the exception? as "escri0e" in Catchin& an" Han".in& Exceptions. % metho" that specifies that it can throw the exception. The metho" must pro$i"e a throws c.ause that .ists the exception? as "escri0e" in Specifyin& the Exceptions Thrown 0y a ,etho". Co"e that fai.s to honor the Catch or Specify Requirement wi.. not compi.e. 3ot a.. exceptions are su0@ect to the Catch or Specify Requirement. To un"erstan" why? we nee" to .oo! at the three 0asic cate&ories of exceptions? on.y one of which is su0@ect to the Requirement.

The Three :inds of Exceptions


The first !in" of exception is the chec!e" exception. These are exceptiona. con"itions that a we..written app.ication shou." anticipate an" reco$er from. For examp.e? suppose an app.ication prompts a user for an input fi.e name? then opens the fi.e 0y passin& the name to the constructor for java.io.FileReader. 3orma..y? the user pro$i"es the name of an existin&? rea"a0.e fi.e? so the construction of the FileReader o0@ect succee"s? an" the execution of the app.ication procee"s norma..y. *ut sometimes the user supp.ies the name of a nonexistent fi.e? an" the constructor throws java.io.FileNotFoundException. % we..-written pro&ram wi.. catch this exception an" notify the user of the mista!e? possi0.y promptin& for a correcte" fi.e name. Chec!e" exceptions are su0@ect to the Catch or Specify Requirement. %.. exceptions are chec!e" exceptions? except for those in"icate" 0y Error? RuntimeException? an" their su0c.asses. The secon" !in" of exception is the error. These are exceptiona. con"itions that are externa. to the app.ication? an" that the app.ication usua..y cannot anticipate or reco$er from. For examp.e? suppose that an app.ication successfu..y opens a fi.e for input? 0ut is una0.e to rea" the fi.e 0ecause of a har"ware or system ma.function. The unsuccessfu. rea" wi.. throw java.io.IOError. %n app.ication mi&ht choose to catch this exception? in or"er to notify the user of the pro0.em # 0ut it a.so mi&ht ma!e sense for the pro&ram to print a stac! trace an" exit. Errors are not su0@ect to the Catch or Specify Requirement. Errors are those exceptions in"icate" 0y Error an" its su0c.asses. The thir" !in" of exception is the runtime exception. These are exceptiona. con"itions that are interna. to the app.ication? an" that the app.ication usua..y cannot anticipate or reco$er from. These usua..y in"icate pro&rammin& 0u&s? such as .o&ic errors or improper use of an %7I. For examp.e? consi"er the app.ication "escri0e" pre$ious.y that passes a fi.e name to the constructor for FileReader. If a .o&ic error causes a null to 0e passe" to the constructor? the constructor wi.. throw NullPointerException. The app.ication can catch this exception? 0ut it pro0a0.y ma!es more sense to e.iminate the 0u& that cause" the exception to occur. Runtime exceptions are not su0@ect to the Catch or Specify Requirement. Runtime exceptions are
8

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.

'ypassin# Catch or Specify


Some pro&rammers consi"er the Catch or Specify Requirement a serious f.aw in the exception mechanism an" 0ypass it 0y usin& unchec!e" exceptions in p.ace of chec!e" exceptions. In &enera.? this is not recommen"e". The section nchec!e" Exceptions # The Contro$ersy ta.!s a0out when it is appropriate to use unchec!e" exceptions.

Catchin# and $and%in# Exceptions


This section "escri0es how to use the three exception han".er components # the try? catch? an" finally 0.oc!s # to write an exception han".er. Then? the try with-resources statement? intro"uce" in >a$a SE 8? is exp.aine". The try with-resources statement is particu.ar.y suite" to situations that use !loseable resources? such as streams. The .ast part of this section wa.!s throu&h an examp.e an" ana.yGes what occurs "urin& $arious scenarios. The fo..owin& examp.e "efines an" imp.ements a c.ass name" "istOfNumbers. When constructe"? "istOfNumbers creates an #rray"ist that contains )2 Inte$er e.ements with sequentia. $a.ues 2 throu&h 9. The "istOfNumbers c.ass a.so "efines a metho" name" write"ist? which writes the .ist of num0ers into a text fi.e ca..e" OutFile.txt. This examp.e uses output c.asses "efine" in java.io? which are co$ere" in *asic IH-.
%%&Note'&This&class&won(t&compile&by&desi$n) import&java.io.*+ import&java.util."ist+ import&java.util.#rray"ist+ public&class&"istOfNumbers&, &&&&private&"ist-Inte$er.&list+ &&&&private&static&final&int&/I0E&1&23+ &&&&public&"istOfNumbers&45&, &&&&&&&&list&1&new&#rray"ist-Inte$er.4/I0E5+ &&&&&&&&for&4int&i&1&3+&i&-&/I0E+&i665&, &&&&&&&&&&&&list.add4new&Inte$er4i55+ &&&&&&&&7 &&&&7 &&&&public&void&write"ist45&, &&&&&&&&Print8riter&out&1&new&Print8riter4new FileWriter("OutFile.txt")5+ &&&&&&&&for&4int&i&1&3+&i&-&/I0E+&i665&, &&&&&&&&&&&&out.println49:alue&at'&9&6&i&6&9&1&9&6&list.get(i)5+ &&&&&&&&7 &&&&&&&&out.close45+ &&&&7 7 9

Catchin& an" Han".in& 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 try '%oc(


The first step in constructin& an exception han".er is to enc.ose the co"e that mi&ht throw an exception within a try 0.oc!. In &enera.? a try 0.oc! .oo!s .i!e the fo..owin&1
try&, &&&&code 7 catch and finally blocks . . .

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%

The catch '%oc(s


Aou associate exception han".ers with a try 0.oc! 0y pro$i"in& one or more catch 0.oc!s "irect.y after the try 0.oc!. 3o co"e can 0e 0etween the en" of the try 0.oc! an" the 0e&innin& of the first catch 0.oc!.
try&, 7&catch&4ExceptionType name5&, 7&catch&4ExceptionType name5&, 7

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

The catch *.oc!s

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!.

The fina%%y '%oc(


The finally 0.oc! a.ways executes when the try 0.oc! exits. This ensures that the finally& 0.oc! is execute" e$en if an unexpecte" exception occurs. *ut finally is usefu. for more than @ust exception han".in& # it a..ows the pro&rammer to a$oi" ha$in& c.eanup co"e acci"enta..y 0ypasse" 0y a return? continue? or brea?. 7uttin& c.eanup co"e in a finally 0.oc! is a.ways a &oo" practice? e$en when no exceptions are anticipate".

<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&not&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.

)+

The try-with-resources Statement

The try,-ith,reso!rces State"ent


The try-with-resources statement is a try statement that "ec.ares one or more resources. % resource is an o0@ect that must 0e c.ose" after the pro&ram is finishe" with it. The try-withresources statement ensures that each resource is c.ose" at the en" of the statement. %ny o0@ect that imp.ements java.lan$.#uto!loseable? which inc.u"es a.. o0@ects which imp.ement java.io.!loseable? can 0e use" as a resource. The fo..owin& examp.e rea"s the first .ine from a fi.e. It uses an instance of ;ufferedReader to rea" "ata from the fi.e. ;ufferedReader is a resource that must 0e c.ose" after the pro&ram is finishe" with it1
static&/trin$&readFirst"ineFromFile4/trin$&path5&throws&IOException&, &&&&try (Buffered eader !r " new Buffered eader(new File eader(path)))&, &&&&&&&&return&br.read"ine45+ &&&&7 7

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%

contains the names of these fi.es1


public&static&void&writeToFile0ipFile!ontents4/trin$&@ipFileNameA &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&/trin$&outputFileName5 &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&throws&java.io.IOException&, &&&&java.nio.charset.!harset&charset&1 &&&&&&&&&java.nio.charset./tandard!harsets.B/C#/!II+ &&&&java.nio.file.Path&outputFilePath&1 &&&&&&&&&java.nio.file.Paths.$et4outputFileName5+ &&&&%%&Open&@ip&file&and&create&output&file&with& &&&&%%&try with resources&statement &&&&try ( #a$a.util.%ip.&ipFile %f " new #a$a.util.%ip.&ipFile(%ipFile'a(e); #a$a.io.BufferedWriter writer " #a$a.nio.file.Files.newBufferedWriter(outputFile)ath* charset) )&, &&&&&&&&%%&Enumerate&each&entry &&&&&&&&for&4java.util.Enumeration&entries&1 &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&@f.entries45+&entries.has<oreElements45+5&, &&&&&&&&&&&&%%&Det&the&entry&name&and&write&it&to&the&output&file &&&&&&&&&&&&/trin$&new"ine&1&/ystem.$etProperty49line.separator95+ &&&&&&&&&&&&/trin$&@ipEntryName&1 &&&&&&&&&&&&&&&&&44java.util.@ip.0ipEntry5entries.nextElement455.$etName45&6 &&&&&&&&&&&&&&&&&new"ine+ &&&&&&&&&&&&writer.write4@ipEntryNameA&3A&@ipEntryName.len$th455+ &&&&&&&&7 &&&&7 7

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 try-with-resources Statement


&&&&&&&&7 &&&&7&catch&4/>"Exception&e5&, &&&&&&&&GF;!TutorialBtilities.print/>"Exception4e5+ &&&&7 7

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!.

C%asses That I"p%e"ent the 0!toC%osea1%e or C%osea1%e Interface


See the >a$a"oc of the #uto!loseable an" !loseable interfaces for a .ist of c.asses that imp.ement either of these interfaces. The !loseable interface exten"s the #uto!loseable& interface. The close metho" of the !loseable interface throws exceptions of type IOException whi.e the close metho" of the #uto!loseable interface throws exceptions of type Exception. Consequent.y? su0c.asses of the #uto!loseable interface can o$erri"e this 0eha$ior of the close metho" to throw specia.iGe" exceptions? such as IOException? or no exception at a...

)/

Excepciones >%C%

/!ttin# It 0%% To#ether


The pre$ious sections "escri0e" how to construct the try? catch? an" finally co"e 0.oc!s for the write"ist metho" in the "istOfNumbers c.ass. 3ow? .etBs wa.! throu&h the co"e an" in$esti&ate what can happen. When a.. the components are put to&ether? the write"ist metho" .oo!s .i!e the fo..owin&.
public&void&write"ist45&, &&&&Print8riter&out&1&null+ &&&&try&, &&&&&&&&/ystem.out.println49Enterin$9&6&9&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&vector.element#t4i55+ &&&&&&&&&&&&&&&&&& &&&&7&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&4out&)1&null5&, &&&&&&&&&&&&/ystem.out.println49!losin$&Print8riter95+ &&&&&&&&&&&&out.close45+ &&&&&&&&7& &&&&&&&&else&, &&&&&&&&&&&&/ystem.out.println49Print8riter&not&open95+ &&&&&&&&7 &&&&7 7

%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.

Scenario 1: 0n Exception ;cc!rs


The statement that creates a File8riter can fai. for a num0er of reasons. For examp.e? the constructor for the File8riter throws an IOException if the pro&ram cannot create or write to the fi.e in"icate". When File8riter throws an IOException? the runtime system imme"iate.y stops executin& the try 0.oc!I metho" ca..s 0ein& execute" are not comp.ete". The runtime system then starts
)5

7uttin& It %.. To&ether

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&not&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%

Scenario &: The try '%oc( Exits <or"a%%y


In this scenario? a.. the statements within the scope of the try 0.oc! execute successfu..y an" throw no exceptions. Execution fa..s off the en" of the try 0.oc!? an" the runtime system passes contro. to the finally 0.oc!. *ecause e$erythin& was successfu.? the Print8riter is open when contro. reaches the finally 0.oc!? which c.oses the Print8riter. %&ain? after the finally 0.oc! finishes executin&? the pro&ram continues with the first statement after the finally 0.oc!. Here is the output from the "istOfNumbers pro&ram when no exceptions are thrown.
Enterin$&try&statement !losin$&Print8riter

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&not&open95+ &&&&&&&&7 &&&&7 7

)9

Specifyin& the Exceptions Thrown 0y a ,etho"

Specifyin# the Exceptions Thro-n 1y a 2ethod


The pre$ious section showe" how to write an exception han".er for the write"ist metho" in the "istOfNumbers c.ass. Sometimes? itBs appropriate for co"e to catch exceptions that can occur within it. In other cases? howe$er? itBs 0etter to .et a metho" further up the ca.. stac! han".e the exception. For examp.e? if you were pro$i"in& the "istOfNumbers c.ass as part of a pac!a&e of c.asses? you pro0a0.y cou."nBt anticipate the nee"s of a.. the users of your pac!a&e. In this case? itBs 0etter to not catch the exception an" to a..ow a metho" further up the ca.. stac! to han".e it. If the write"ist metho" "oesnBt catch the chec!e" exceptions that can occur within it? the write"ist metho" must specify that it can throw these exceptions. 6etBs mo"ify the ori&ina. write"ist metho" to specify the exceptions it can throw instea" of catchin& them. To remin" you? hereBs the ori&ina. $ersion of the write"ist metho" that wonBt compi.e.
%%&Note'&This&method&won(t&compile&by&desi$n) public&void&write"ist45&, &&&&Print8riter&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&vector.element#t4i55+ &&&&7 &&&&out.close45+ 7

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%

$o- to Thro- Exceptions


*efore you can catch an exception? some co"e somewhere must throw one. %ny co"e can throw an exception1 your co"e? co"e from a pac!a&e written 0y someone e.se such as the pac!a&es that come with the >a$a p.atform? or the >a$a runtime en$ironment. Re&ar".ess of what throws the exception? itBs a.ways thrown with the throw statement. %s you ha$e pro0a0.y notice"? the >a$a p.atform pro$i"es numerous exception c.asses. %.. the c.asses are "escen"ants of the Throwable c.ass? an" a.. a..ow pro&rams to "ifferentiate amon& the $arious types of exceptions that can occur "urin& the execution of a pro&ram. Aou can a.so create your own exception c.asses to represent pro0.ems that can occur within the c.asses you write. In fact? if you are a pac!a&e "e$e.oper? you mi&ht ha$e to create your own set of exception c.asses to a..ow users to "ifferentiate an error that can occur in your pac!a&e from errors that occur in the >a$a p.atform or other pac!a&es. Aou can a.so create chaine" exceptions. For more information? see the Chaine" Exceptions section.

The thro- State"ent


%.. metho"s use the throw statement to throw an exception. The throw statement requires a sin&.e ar&ument1 a throwa0.e o0@ect. Throwa0.e o0@ects are instances of any su0c.ass of the Throwable c.ass. HereBs an examp.e of a throw statement.
throw&someThrowableObject+

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

How to Throw Exceptions

Thro-a1%e C%ass and Its S!1c%asses


The o0@ects that inherit from the Throwable c.ass inc.u"e "irect "escen"ants Do0@ects that inherit "irect.y from the Throwable c.assE an" in"irect "escen"ants Do0@ects that inherit from chi."ren or &ran"chi."ren of the Throwable c.assE. The fi&ure 0e.ow i..ustrates the c.ass hierarchy of the Throwable c.ass an" its most si&nificant su0c.asses. %s you can see? Throwable has two "irect "escen"ants1 Error an" Exception.

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.

0ccessin# Stac( Trace Infor"ation


3ow .etBs suppose that the hi&her-.e$e. exception han".er wants to "ump the stac! trace in its own format.

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%

Creatin# Exception C%asses


When face" with choosin& the type of exception to throw? you can either use one written 0y someone e.se # the >a$a p.atform pro$i"es a .ot of exception c.asses you can use # or you can write one of your own. Aou shou." write your own exception c.asses if you answer yes to any of the fo..owin& questionsI otherwise? you can pro0a0.y use someone e.seBs. =o you nee" an exception type that isnBt represente" 0y those in the >a$a p.atform? Wou." it he.p users if they cou." "ifferentiate your exceptions from those thrown 0y c.asses written 0y other $en"ors? =oes your co"e throw more than one re.ate" exception? If you use someone e.seBs exceptions? wi.. users ha$e access to those exceptions? % simi.ar question is? shou." your pac!a&e 0e in"epen"ent an" se.f-containe"?

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&ether. 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

Creatin& Exception C.asses

<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.

4nchec(ed Exceptions 5 The Contro6ersy


*ecause the >a$a pro&rammin& .an&ua&e "oes not require metho"s to catch or to specify unchec!e" exceptions DRuntimeException? Error? an" their su0c.assesE? pro&rammers may 0e tempte" to write co"e that throws on.y unchec!e" exceptions or to ma!e a.. their exception su0c.asses inherit from RuntimeException. *oth of these shortcuts a..ow pro&rammers to write co"e without 0otherin& with compi.er errors an" without 0otherin& to specify or to catch any exceptions. %.thou&h this may seem con$enient to the pro&rammer? it si"esteps the intent of the catch or specify requirement an" can cause pro0.ems for others usin& your c.asses. Why "i" the "esi&ners "eci"e to force a metho" to specify a.. uncau&ht chec!e" exceptions that can 0e thrown within its scope? %ny Exception that can 0e thrown 0y a metho" is part of the metho"Bs pu0.ic pro&rammin& interface. Those who ca.. a metho" must !now a0out the exceptions that a metho" can throw so that they can "eci"e what to "o a0out them. These exceptions are as much a part of that metho"Bs pro&rammin& interface as its parameters an" return $a.ue. The next question mi&ht 0e1 :If itBs so &oo" to "ocument a metho"Bs %7I? inc.u"in& the exceptions it can throw? why not specify runtime exceptions too?: Runtime exceptions represent pro0.ems that are the resu.t of a pro&rammin& pro0.em? an" as such? the %7I c.ient co"e cannot reasona0.y 0e expecte" to reco$er from them or to han".e them in any way. Such pro0.ems inc.u"e arithmetic exceptions? such as "i$i"in& 0y GeroI pointer exceptions? such as tryin& to access an o0@ect throu&h a nu.. referenceI an" in"exin& exceptions? such as attemptin& to access an array e.ement throu&h an in"ex that is too .ar&e or too sma... Runtime exceptions can occur anywhere in a pro&ram? an" in a typica. one they can 0e $ery numerous. Ha$in& to a"" runtime exceptions in e$ery metho" "ec.aration wou." re"uce a pro&ramBs c.arity. Thus? the compi.er "oes not require that you catch or specify runtime exceptions Da.thou&h you canE. -ne case where it is common practice to throw a RuntimeException is when the user ca..s a metho" incorrect.y. For examp.e? a metho" can chec! if one of its ar&uments is incorrect.y null. If an ar&ument is null? the metho" mi&ht throw a NullPointerException? which is an unchec!e" exception. <enera..y spea!in&? "o not throw a RuntimeException or create a su0c.ass of RuntimeException simp.y 0ecause you "onBt want to 0e 0othere" with specifyin& the exceptions your metho"s can throw. HereBs the 0ottom .ine &ui"e.ine1 If a c.ient can reasona0.y 0e expecte" to reco$er from an exception? ma!e it a chec!e" exception. If a c.ient cannot "o anythin& to reco$er from the exception? ma!e it an unchec!e" exception.

+/

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.

0d6anta#e 1: Separatin# Error,$and%in# Code fro" =Re#!%ar= Code


Exceptions pro$i"e the means to separate the "etai.s of what to "o when somethin& out of the or"inary happens from the main .o&ic of a pro&ram. In tra"itiona. pro&rammin&? error "etection? reportin&? an" han".in& often .ea" to confusin& spa&hetti co"e. For examp.e? consi"er the pseu"oco"e metho" here that rea"s an entire fi.e into memory.
readFile&, &&&&open the file; determine its size; allocate that much memory; read the file into memory; close the file; 7

%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.

0d6anta#e &: /ropa#atin# Errors 4p the Ca%% Stac(


% secon" a"$anta&e of exceptions is the a0i.ity to propa&ate error reportin& up the ca.. stac! of metho"s. Suppose that the readFile metho" is the fourth metho" in a series of neste" metho" ca..s ma"e 0y the main pro&ram1 method2 ca..s methodK? which ca..s methodL? which fina..y ca..s readFile.
method2&, &&&&call method2; 7 methodK&, &&&&call method3; 7 +8

Excepciones >%C%

methodL&, &&&&call readFile; 7

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.

0d6anta#e ): >ro!pin# and 9ifferentiatin# Error Types


*ecause a.. exceptions thrown within a pro&ram are o0@ects? the &roupin& or cate&oriGin& of exceptions is a natura. outcome of the c.ass hierarchy. %n examp.e of a &roup of re.ate" exception c.asses in the >a$a p.atform are those "efine" in java.io # IOException an" its "escen"ants. IOException is the most &enera. an" represents any type of error that can occur when performin& IH-. Its "escen"ants represent more specific errors. For examp.e? FileNotFoundException means that a fi.e cou." not 0e .ocate" on "is!. % metho" can write specific han".ers that can han".e a $ery specific exception. The FileNotFoundException c.ass has no "escen"ants? so the fo..owin& han".er can han".e on.y one type of exception.
catch&4FileNotFoundException&e5&, &&&&... 7

% 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.

8!estions and Exercises


8!estions
). Is the fo..owin& co"e .e&a.?
try&, &&&& 7&finally&, &&&& 7

+. What exception types can 0e cau&ht 0y the fo..owin& han".er?


catch&4Exception&e5&, &&&&& 7

;2

'uestions an" Exercises

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

;)

You might also like