Você está na página 1de 12

8/27/2015

JavaExceptions

JAVAEXCEPTIONS
Copyrighttutorialspoint.com

http://www.tutorialspoint.com/java/java_exceptions.htm

Anexceptionorexceptionaleventisaproblemthatarisesduringtheexecutionofaprogram.Whenan
Exceptionoccursthenormalflowoftheprogramisdisruptedandtheprogram/Applicationterminates
abnormally,whichisnotrecommended,thereforetheseexceptionsaretobehandled.
Anexceptioncanoccurformanydifferentreasons,belowgivenaresomescenarioswhereexceptionoccurs.
Auserhasenteredinvaliddata.
Afilethatneedstobeopenedcannotbefound.
AnetworkconnectionhasbeenlostinthemiddleofcommunicationsortheJVMhasrunoutof
memory.
Someoftheseexceptionsarecausedbyusererror,othersbyprogrammererror,andothersbyphysical
resourcesthathavefailedinsomemanner.
BasedonthesewehavethreecategoriesofExceptionsyouneedtounderstandthemtoknowhowexception
handlingworksinJava,
Checkedexceptions:Acheckedexceptionisanexceptionthatoccursatthecompiletime,theseare
alsocalledascompiletimeexceptions.Theseexceptionscannotsimplybeignoredatthetimeof
compilation,theProgrammershouldtakecareofhandle theseexceptions.
Forexample,ifyouuseFileReaderclassinyourprogramtoreaddatafromafile,ifthefilespecified
initsconstructordoesn'texist,thenanFileNotFoundExceptionoccurs,andcompilerpromptsthe
programmertohandletheexception.
importjava.io.File;
importjava.io.FileReader;
publicclassFilenotFound_Demo{
publicstaticvoidmain(Stringargs[]){
Filefile=newFile("E://file.txt");
FileReaderfr=newFileReader(file);
}

Ifyoutrytocompiletheaboveprogramyouwillgetexceptionsasshownbelow.

C:\>javacFilenotFound_Demo.java
FilenotFound_Demo.java:8:error:unreportedexceptionFileNotFoundException;mustbecaught
ordeclaredtobethrown
FileReaderfr=newFileReader(file);

http://www.tutorialspoint.com/cgibin/printpage.cgi

1/12

8/27/2015

JavaExceptions

^
1error

NoteSincethemethodsreadandcloseofFileReaderclassthrowsIOException,youcanobservethat
compilernotifiestohandleIOException,alongwithFileNotFoundException.
Uncheckedexceptions:AnUncheckedexceptionisanexceptionthatoccursatthetimeof
execution,thesearealsocalledasRuntimeExceptions,theseincludeprogrammingbugs,suchaslogic
errorsorimproperuseofanAPI.runtimeexceptionsareignoredatthetimeofcompilation.
Forexample,ifyouhavedeclaredanarrayofsize5inyourprogram,andtryingtocallthe6thelement
ofthearraythenanArrayIndexOutOfBoundsExceptionexceptionoccurs.
publicclassUnchecked_Demo{

publicstaticvoidmain(Stringargs[]){
intnum[]={1,2,3,4};
System.out.println(num[5]);
}
}

Ifyoucompileandexecutetheaboveprogramyouwillgetexceptionasshownbelow.
Exceptioninthread"main"java.lang.ArrayIndexOutOfBoundsException:5

atExceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

ErrorsThesearenotexceptionsatall,butproblemsthatarisebeyondthecontroloftheuseror
theprogrammer.Errorsaretypicallyignoredinyourcodebecauseyoucanrarelydoanythingabout
anerror.Forexample,ifastackoverflowoccurs,anerrorwillarise.Theyarealsoignoredatthetime
ofcompilation.

ExceptionHierarchy
Allexceptionclassesaresubtypesofthejava.lang.Exceptionclass.Theexceptionclassisasubclassofthe
Throwableclass.OtherthantheexceptionclassthereisanothersubclasscalledErrorwhichisderivedfrom
theThrowableclass.
ErrorsarenotnormallytrappedformtheJavaprograms.Theseconditionsnormallyhappenincaseof
severefailures,whicharenothandledbythejavaprograms.Errorsaregeneratedtoindicateerrors
generatedbytheruntimeenvironment.Example:JVMisoutofMemory.Normallyprogramscannot
recoverfromerrors.
TheExceptionclasshastwomainsubclasses:IOExceptionclassandRuntimeExceptionClass.

http://www.tutorialspoint.com/cgibin/printpage.cgi

2/12

8/27/2015

JavaExceptions

HereisalistofmostcommoncheckedanduncheckedJava'sBuiltinExceptions.

ExceptionsMethods
FollowingisthelistofimportantmedthodsavailableintheThrowableclass.

SN

MethodswithDescription

publicStringgetMessage
Returnsadetailedmessageabouttheexceptionthathasoccurred.Thismessageisinitializedinthe
Throwableconstructor.

publicThrowablegetCause
ReturnsthecauseoftheexceptionasrepresentedbyaThrowableobject.

publicStringtoString
ReturnsthenameoftheclassconcatenatedwiththeresultofgetMessage

publicvoidprintStackTrace

http://www.tutorialspoint.com/cgibin/printpage.cgi

3/12

8/27/2015

JavaExceptions

PrintstheresultoftoStringalongwiththestacktracetoSystem.err,theerroroutputstream.
5

publicStackTraceElement[]getStackTrace
Returnsanarraycontainingeachelementonthestacktrace.Theelementatindex0representsthe
topofthecallstack,andthelastelementinthearrayrepresentsthemethodatthebottomofthe
callstack.

publicThrowablefillInStackTrace
FillsthestacktraceofthisThrowableobjectwiththecurrentstacktrace,addingtoanyprevious
informationinthestacktrace.

CatchingExceptions:
Amethodcatchesanexceptionusingacombinationofthetryandcatchkeywords.Atry/catchblockis
placedaroundthecodethatmightgenerateanexception.Codewithinatry/catchblockisreferredtoas
protectedcode,andthesyntaxforusingtry/catchlookslikethefollowing:
try
{
//Protectedcode
}catch(ExceptionNamee1)
{
//Catchblock
}

Thecodewhichispronetoexceptionsisplacedinthetryblock,whenanexceptionoccurs,thatexception
occurredishandledbycatchblockassociatedwithit.Everytryblockshouldbeimmediatelyfollowedeither
byaclassblockorfinallyblock.
Acatchstatementinvolvesdeclaringthetypeofexceptionyouaretryingtocatch.Ifanexceptionoccursin
protectedcode,thecatchblockorblocksthatfollowsthetryischecked.Ifthetypeofexceptionthatoccurred
islistedinacatchblock,theexceptionispassedtothecatchblockmuchasanargumentispassedintoa
methodparameter.

Example
Thefollowingisanarrayisdeclaredwith2elements.Thenthecodetriestoaccessthe3rdelementofthe
arraywhichthrowsanexception.
//FileName:ExcepTest.java
importjava.io.*;
publicclassExcepTest{

http://www.tutorialspoint.com/cgibin/printpage.cgi

4/12

8/27/2015

JavaExceptions

publicstaticvoidmain(Stringargs[]){
try{
inta[]=newint[2];
System.out.println("Accesselementthree:"+a[3]);
}catch(ArrayIndexOutOfBoundsExceptione){
System.out.println("Exceptionthrown:"+e);
}
System.out.println("Outoftheblock");
}
}

Thiswouldproducethefollowingresult:
Exceptionthrown:java.lang.ArrayIndexOutOfBoundsException:3
Outoftheblock

MultiplecatchBlocks:
Atryblockcanbefollowedbymultiplecatchblocks.Thesyntaxformultiplecatchblockslookslikethe
following
try
{
//Protectedcode
}catch(ExceptionType1e1)
{
//Catchblock
}catch(ExceptionType2e2)
{
//Catchblock
}catch(ExceptionType3e3)
{
//Catchblock
}

Thepreviousstatementsdemonstratethreecatchblocks,butyoucanhaveanynumberofthemafterasingle
try.Ifanexceptionoccursintheprotectedcode,theexceptionisthrowntothefirstcatchblockinthelist.If
thedatatypeoftheexceptionthrownmatchesExceptionType1,itgetscaughtthere.Ifnot,theexception
passesdowntothesecondcatchstatement.Thiscontinuesuntiltheexceptioneitheriscaughtorfalls
throughallcatches,inwhichcasethecurrentmethodstopsexecutionandtheexceptionisthrowndownto
thepreviousmethodonthecallstack.

Example
Hereiscodesegmentshowinghowtousemultipletry/catchstatements.
try
{
file=newFileInputStream(fileName);
x=(byte)file.read();
}catch(IOExceptioni)

http://www.tutorialspoint.com/cgibin/printpage.cgi

5/12

8/27/2015

JavaExceptions

{
i.printStackTrace();
return1;
}catch(FileNotFoundExceptionf)//Notvalid!
{
f.printStackTrace();
return1;
}

Catchingmultipletypeofexceptions
SinceJava7youcanhandlemorethanoneexceptionsusingasinglecatchblock,thisfeaturesimplifiesthe
code.Belowgivenisthesyntaxofwriting.
catch(IOException|FileNotFoundExceptionex){
logger.log(ex);
throwex;

Thethrows/throwKeywords:
Ifamethoddoesnothandleacheckedexception,themethodmustdeclareitusingthethrowskeyword.
Thethrowskeywordappearsattheendofamethod'ssignature.
Youcanthrowanexception,eitheranewlyinstantiatedoneoranexceptionthatyoujustcaught,byusing
thethrowkeyword.
Trytounderstandthedifferencebetweenthrowsandthrowkeywords,throwsisusedtopostponethe
handlingofacheckedexceptionandthrowisusedtoinvokeanexceptionexplicitly.
ThefollowingmethoddeclaresthatitthrowsaRemoteException
importjava.io.*;
publicclassclassName
{
publicvoiddeposit(doubleamount)throwsRemoteException
{
//Methodimplementation
thrownewRemoteException();
}
//Remainderofclassdefinition
}

Amethodcandeclarethatitthrowsmorethanoneexception,inwhichcasetheexceptionsaredeclaredina
listseparatedbycommas.Forexample,thefollowingmethoddeclaresthatitthrowsaRemoteException
andanInsufficientFundsException
importjava.io.*;
publicclassclassName
{

http://www.tutorialspoint.com/cgibin/printpage.cgi

6/12

8/27/2015

JavaExceptions

publicvoidwithdraw(doubleamount)throwsRemoteException,
InsufficientFundsException
{
//Methodimplementation
}
//Remainderofclassdefinition
}

Thefinallyblock
Thefinallyblockfollowsatryblockoracatchblock.Afinallyblockofcodealwaysexecutes,irrespectiveof
occurrenceofanException.
Usingafinallyblockallowsyoutorunanycleanuptypestatementsthatyouwanttoexecute,nomatterwhat
happensintheprotectedcode.
Afinallyblockappearsattheendofthecatchblocksandhasthefollowingsyntax
try
{
//Protectedcode
}catch(ExceptionType1e1)
{
//Catchblock
}catch(ExceptionType2e2)
{
//Catchblock
}catch(ExceptionType3e3)
{
//Catchblock
}finally
{
//Thefinallyblockalwaysexecutes.
}

Example
publicclassExcepTest{
publicstaticvoidmain(Stringargs[]){
inta[]=newint[2];
try{
System.out.println("Accesselementthree:"+a[3]);
}catch(ArrayIndexOutOfBoundsExceptione){
System.out.println("Exceptionthrown:"+e);
}
finally{
a[0]=6;
System.out.println("Firstelementvalue:"+a[0]);
System.out.println("Thefinallystatementisexecuted");
}
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

7/12

8/27/2015

JavaExceptions

Thiswouldproducethefollowingresult
Exceptionthrown:java.lang.ArrayIndexOutOfBoundsException:3
Firstelementvalue:6
Thefinallystatementisexecuted

Notethefollowing
Acatchclausecannotexistwithoutatrystatement.
Itisnotcompulsorytohavefinallyclauseswheneveratry/catchblockispresent.
Thetryblockcannotbepresentwithouteithercatchclauseorfinallyclause.
Anycodecannotbepresentinbetweenthetry,catch,finallyblocks.

Thetrywithresources
Generallywhenweuseanyresourceslikestreams,connectionsetc..wehavetoclosethemexplicitlyusing
finallyblock.IntheprogramgivenbelowwearereadingdatafromafileusingFileReaderandweare
closingitusingfinallyblock.
importjava.io.File;
importjava.io.FileReader;
importjava.io.IOException;
publicclassReadData_Demo{
publicstaticvoidmain(Stringargs[]){
FileReaderfr=null;

try{
Filefile=newFile("E://file.txt");
fr=newFileReader(file);char[]a=newchar[50];
fr.read(a);//readsthecontenttothearray
for(charc:a)
System.out.print(c);//printsthecharactersonebyone
}catch(IOExceptione){
e.printStackTrace();
}
finally{
try{
fr.close();
}catch(IOExceptionex){

ex.printStackTrace();
}
}
}
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

8/12

8/27/2015

JavaExceptions

trywithresources,alsoreferredasautomaticresourcemanagement.isanewexceptionhandling
mechanismthatwasintroducedinJava7,whichautomaticallyclosestheresourcesusedwithinthetrycatch
block.
Tousethisstatementyousimplyneedtodeclaretherequiredresourceswithintheparenthesis,thecreated
resourcewillbeclosedautomaticallyattheendoftheblock,belowgivenisthesyntaxoftrywithresources
statement.
try(FileReaderfr=newFileReader("filepath"))
{
//usetheresource
}catch(){
//bodyofcatch
}
}

Belowgivenistheprogramthatreadsthedatainafileusingtrywithresourcesstatement.
importjava.io.FileReader;
importjava.io.IOException;
publicclassTry_withDemo{
publicstaticvoidmain(Stringargs[]){

try(FileReaderfr=newFileReader("E://file.txt")){
char[]a=newchar[50];
fr.read(a);//readsthecontenttothearray
for(charc:a)
System.out.print(c);//printsthecharactersonebyone
}catch(IOExceptione){
e.printStackTrace();
}

}
}

Followingpointsaretobekeptinmindwhileworkingwithtrywithresourcesstatement.
TouseaclasswithtrywithresourcesstatementitshouldimplementAutoCloseableinterfaceand
theclosemethodofitgetsinvokedautomaticallyatruntime.
Youcandeclaremorethanoneclassintrywithresourcesstatement.
whileyoudeclaremultipleclassesinthetryblockoftrywithresourcesstatementtheseclassesare
closedinreverseorder.
Exceptthedecelerationofresourceswithintheparenthesiseverythingissameasnormaltry/catch
blockofatryblock.
Theresourcedeclaredintrygetsinstantiatedjustbeforethestartofthetryblock.

http://www.tutorialspoint.com/cgibin/printpage.cgi

9/12

8/27/2015

JavaExceptions

Theresourcedeclaredatthetryblockisimplicitlydeclaredasfinal.

UserdefinedExceptions:
YoucancreateyourownexceptionsinJava.Keepthefollowingpointsinmindwhenwritingyourown
exceptionclasses
AllexceptionsmustbeachildofThrowable.
IfyouwanttowriteacheckedexceptionthatisautomaticallyenforcedbytheHandleorDeclareRule,
youneedtoextendtheExceptionclass.
Ifyouwanttowritearuntimeexception,youneedtoextendtheRuntimeExceptionclass.
WecandefineourownExceptionclassasbelow
classMyExceptionextendsException{
}

YoujustneedtoextendthepredefinedExceptionclasstocreateyourownException.Theseareconsidered
tobecheckedexceptions.ThefollowingInsufficientFundsExceptionclassisauserdefinedexception
thatextendstheExceptionclass,makingitacheckedexception.Anexceptionclassislikeanyotherclass,
containingusefulfieldsandmethods.

Example
//FileNameInsufficientFundsException.java
importjava.io.*;
publicclassInsufficientFundsExceptionextendsException
{
privatedoubleamount;
publicInsufficientFundsException(doubleamount)
{
this.amount=amount;
}
publicdoublegetAmount()
{
returnamount;
}
}

Todemonstrateusingouruserdefinedexception,thefollowingCheckingAccountclasscontainsawithdraw
methodthatthrowsanInsufficientFundsException.
//FileNameCheckingAccount.java
importjava.io.*;
publicclassCheckingAccount
{
privatedoublebalance;

http://www.tutorialspoint.com/cgibin/printpage.cgi

10/12

8/27/2015

JavaExceptions

privateintnumber;
publicCheckingAccount(intnumber)
{
this.number=number;
}
publicvoiddeposit(doubleamount)
{
balance+=amount;
}
publicvoidwithdraw(doubleamount)throws
InsufficientFundsException
{
if(amount<=balance)
{
balance=amount;
}
else
{
doubleneeds=amountbalance;
thrownewInsufficientFundsException(needs);
}
}
publicdoublegetBalance()
{
returnbalance;
}
publicintgetNumber()
{
returnnumber;
}
}

ThefollowingBankDemoprogramdemonstratesinvokingthedepositandwithdrawmethodsof
CheckingAccount.
//FileNameBankDemo.java
publicclassBankDemo
{
publicstaticvoidmain(String[]args)
{
CheckingAccountc=newCheckingAccount(101);
System.out.println("Depositing$500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing$100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing$600...");
c.withdraw(600.00);
}catch(InsufficientFundsExceptione)
{
System.out.println("Sorry,butyouareshort$"
+e.getAmount());

http://www.tutorialspoint.com/cgibin/printpage.cgi

11/12

8/27/2015

JavaExceptions

e.printStackTrace();
}
}
}

CompilealltheabovethreefilesandrunBankDemo,thiswouldproducethefollowingresult
Depositing$500...
Withdrawing$100...
Withdrawing$600...
Sorry,butyouareshort$200.0
InsufficientFundsException
atCheckingAccount.withdraw(CheckingAccount.java:25)
atBankDemo.main(BankDemo.java:13)

CommonExceptions
InJava,itispossibletodefinetwocatergoriesofExceptionsandErrors.
JVMExceptionsTheseareexceptions/errorsthatareexclusivelyorlogicallythrownbytheJVM.
Examples:NullPointerException,ArrayIndexOutOfBoundsException,ClassCastException,
ProgrammaticexceptionsTheseexceptionsarethrownexplicitlybytheapplicationortheAPI
programmersExamples:IllegalArgumentException,IllegalStateException.

http://www.tutorialspoint.com/cgibin/printpage.cgi

12/12

Você também pode gostar