Exceptions in JavaWord文档下载推荐.docx

上传人:b****5 文档编号:20043978 上传时间:2023-01-16 格式:DOCX 页数:27 大小:63.47KB
下载 相关 举报
Exceptions in JavaWord文档下载推荐.docx_第1页
第1页 / 共27页
Exceptions in JavaWord文档下载推荐.docx_第2页
第2页 / 共27页
Exceptions in JavaWord文档下载推荐.docx_第3页
第3页 / 共27页
Exceptions in JavaWord文档下载推荐.docx_第4页
第4页 / 共27页
Exceptions in JavaWord文档下载推荐.docx_第5页
第5页 / 共27页
点击查看更多>>
下载资源
资源描述

Exceptions in JavaWord文档下载推荐.docx

《Exceptions in JavaWord文档下载推荐.docx》由会员分享,可在线阅读,更多相关《Exceptions in JavaWord文档下载推荐.docx(27页珍藏版)》请在冰豆网上搜索。

Exceptions in JavaWord文档下载推荐.docx

thandleitself,itmaythrowanexception.Throwinganexceptionislikethrowingabeeping,flashingredballtoindicatethereisaproblemthatcan'

tbehandledwhereitoccurred.Somewhere,youhope,thisballwillbecaughtandtheproblemwillbedealtwith.Exceptionsarecaughtbyhandlerspositionedalongthethread'

smethodinvocationstack.Ifthecallingmethodisn'

tpreparedtocatchtheexception,itthrowstheexceptionuptoitscallingmethod,andsoon.Ifoneofthethreadsofyourprogramthrowsanexceptionthatisn'

tcaughtbyanymethodalongthemethodinvocationstack,thatthreadwillexpire.WhenyouprograminJava,youmustpositioncatchers(theexceptionhandlers)strategically,soyourprogramwillcatchandhandleallexceptionsfromwhichyouwantyourprogramtorecover.

Exceptionclasses

InJava,exceptionsareobjects.Whenyouthrowanexception,youthrowanobject.Youcan'

tthrowjustanyobjectasanexception,however--onlythoseobjectswhoseclassesdescendfromThrowable.Throwableservesasthebaseclassforanentirefamilyofclasses,declaredinjava.lang,thatyourprogramcaninstantiateandthrow.Asmallpartofthisfamilyisshownin

图表1ApartialviewoftheThrowablefamily

AsyoucanseeinFigure1,Throwablehastwodirectsubclasses,ExceptionandError.Exceptions(membersoftheExceptionfamily)arethrowntosignalabnormalconditionsthatcanoftenbehandledbysomecatcher,thoughit'

spossibletheymaynotbecaughtandthereforecouldresultinadeadthread.Errors(membersoftheErrorfamily)areusuallythrownformoreseriousproblems,suchasOutOfMemoryError,thatmaynotbesoeasytohandle.Ingeneral,codeyouwriteshouldthrowonlyexceptions,noterrors.ErrorsareusuallythrownbythemethodsoftheJavaAPI,orbytheJavavirtualmachineitself.

Inadditiontothrowingobjectswhoseclassesaredeclaredinjava.lang,youcanthrowobjectsofyourowndesign.Tocreateyourownclassofthrowableobjects,youneedonlydeclareitasasubclassofsomememberoftheThrowablefamily.Ingeneral,however,thethrowableclassesyoudefineshouldextendclassException.Theyshouldbe"

exceptions."

Thereasoningbehindthisrulewillbeexplainedlaterinthisarticle.

Whetheryouuseanexistingexceptionclassfromjava.langorcreateoneofyourowndependsuponthesituation.Insomecases,aclassfromjava.langwilldojustfine.Forexample,ifoneofyourmethodsisinvokedwithaninvalidargument,youcouldthrowIllegalArgumentException,asubclassofRuntimeExceptioninjava.lang.

Othertimes,however,youwillwanttoconveymoreinformationabouttheabnormalconditionthanaclassfromjava.langwillallow.Usually,theclassoftheexceptionobjectitselfindicatesthetypeofabnormalconditionthatwasencountered.Forexample,ifathrownexceptionobjecthasclassIllegalArgumentException,thatindicatessomeonepassedanillegalargumenttoamethod.Sometimesyouwillwanttoindicatethatamethodencounteredanabnormalconditionthatisn'

trepresentedbyaclassintheThrowablefamilyofjava.lang.

Asanexample,imagineyouarewritingaJavaprogramthatsimulatesacustomerofavirtualcafé

drinkingacupofcoffee.Considertheexceptionalconditionsthatmightoccurwhilethecustomersips.TheclasshierarchyofexceptionsshowninFigure2representsafewpossibilities.

 

Figure2.Exceptionhierarchyforcoffeesipping

Ifthecustomerdiscovers,withdismay,thatthecoffeeiscold,yourprogramcouldthrowaTooColdException.Ontheotherhand,ifthecustomerdiscoversthatthecoffeeisoverlyhot,yourprogramcouldthrowaTooHotException.Theseconditionscouldbeexceptionsbecausetheyare(hopefully)notthenormalsituationinyourcafé

.(Exceptionalconditionsarenotnecessarilyrare,justoutsidethenormalflowofevents.)Thecodeforyournewexceptionclassesmightlooklikethis:

//InSourcePacketinfileexcept/ex1/TemperatureException.java

classTemperatureExceptionextendsException{

}

//InSourcePacketinfileexcept/ex1/TooColdException.java

classTooColdExceptionextendsTemperatureException{

//InSourcePacketinfileexcept/ex1/TooHotException.java

classTooHotExceptionextendsTemperatureException{

Thisfamilyofclasses,theTemperatureExceptionfamily,declaresthreenewtypesofexceptionsforyourprogramtothrow.Notethateachexceptionindicatesbyitsclassthekindofabnormalconditionthatwouldcauseittobethrown:

TemperatureExceptionindicatessomekindofproblemwithtemperature;

TooColdExceptionindicatessomethingwastoocold;

andTooHotExceptionindicatessomethingwastoohot.NotealsothatTemperatureExceptionextendsException--notThrowable,Error,oranyotherclassdeclaredinjava.lang.

Throwingexceptions

Tothrowanexception,yousimplyusethethrowkeywordwithanobjectreference,asin:

thrownewTooColdException();

ThetypeofthereferencemustbeThrowableoroneofitssubclasses.

Thefollowingcodeshowshowaclassthatrepresentsthecustomer,classVirtualPerson,mightthrowexceptionsifthecoffeedidn'

tmeetthecustomer'

stemperaturepreferences.NotethatJavaalsohasathrowskeywordinadditiontothethrowkeyword.Onlythrowcanbeusedtothrowanexception.Themeaningofthrowswillbeexplainedlaterinthisarticle.

//InSourcePacketinfileexcept/ex1/VirtualPerson.java

classVirtualPerson{

privatestaticfinalinttooCold=65;

privatestaticfinalinttooHot=85;

publicvoiddrinkCoffee(CoffeeCupcup)throws

TooColdException,TooHotException{

inttemperature=cup.getTemperature();

if(temperature<

=tooCold){

thrownewTooColdException();

}

elseif(temperature>

=tooHot){

thrownewTooHotException();

//...

//InSourcePacketinfileexcept/ex1/CoffeeCup.java

classCoffeeCup{

//75degreesCelsius:

thebesttemperatureforcoffee

privateinttemperature=75;

publicvoidsetTemperature(intval){

temperature=val;

publicintgetTemperature(){

returntemperature;

Catchingexceptions

TocatchanexceptioninJava,youwriteatryblockwithoneormorecatchclauses.Eachcatchclausespecifiesoneexceptiontypethatitispreparedtohandle.Thetryblockplacesafencearoundabitofcodethatisunderthewatchfuleyeoftheassociatedcatchers.Ifthebitofcodedelimitedbythetryblockthrowsanexception,theassociatedcatchclauseswillbeexaminedbytheJavavirtualmachine.Ifthevirtualmachinefindsacatchclausethatispreparedtohandlethethrownexception,theprogramcontinuesexecutionstartingwiththefirststatementofthatcatchclause.

Asanexample,consideraprogramthatrequiresoneargumentonthecommandline,astringthatcanbeparsedintoaninteger.WhenyouhaveaStringandwantanint,youcaninvoketheparseInt()methodoftheIntegerclass.Ifthestringyoupassrepresentsaninteger,parseInt()willreturnthevalue.Ifthestringdoesn'

trepresentaninteger,parseInt()throwsNumberFormatException.Hereishowyoumightparseanintfromacommand-lineargument:

//InSourcePacketinfileexcept/ex1/Example1.java

classExample1{

publicstaticvoidmain(String[]args){

inttemperature=0;

if(args.length>

0){

try{

temperature=Integer.parseInt(args[0]);

catch(NumberFormatExceptione){

System.out.println(

"

Mustenterintegerasfirstargument."

);

return;

else{

Mustentertemperatureasfirstargument."

//Createanewcoffeecupandsetthetemperatureof

//itscoffee.

CoffeeCupcup=newCoffeeCup();

cup.setTemperature(temperature);

//Createandserveavirtualcustomer.

VirtualPersoncust=newVirtualPerson();

VirtualCafe.serveCustomer(cust,cup);

Here,theinvocationofparseInt()sitsinsideatryblock.AttachedtothetryblockisacatchclausethatcatchesNumberFormatException:

catch(NumberFormatExceptione){

Thelowercasecharactereisareferencetothethrown(andcaught)NumberFormatExceptionobject.Thisreferencecouldhavebeenusedinsidethecatchclause,althoughinthiscaseitisn'

t.(Examplesofcatchclausesthatusethereferenceareshownlaterinthisarticle.)

IftheusertypesHarumphasthefirstargumenttotheExample1program,parseInt()willthrowaNumberFormatExceptionexceptionandthecatchclausewillcatchit.Theprogramwillprint:

Mustenterintegerasfirstargument.

Althoughtheaboveexamplehadonlyonecatchclause,youcanhavemanycatchclausesassociatedwithasingletryblock.Here'

sanexample:

//InSourcePacketinfileexcept/ex1/VirtualCafe.java

classVirtualCafe{

publicstaticvoidserveCustomer(VirtualPersoncust,

CoffeeCupcup){

cust.drinkCoffee(cup);

System.out.println("

Coffeeisjustright."

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 初中教育 > 语文

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1