课件Java程序设计方案.ppt

上传人:京东小超市 文档编号:6056072 上传时间:2020-09-01 格式:PPT 页数:47 大小:272.50KB
返回 下载 相关 举报
课件Java程序设计方案.ppt_第1页
第1页 / 共47页
课件Java程序设计方案.ppt_第2页
第2页 / 共47页
亲,该文档总共47页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

《课件Java程序设计方案.ppt》由会员分享,可在线阅读,更多相关《课件Java程序设计方案.ppt(47页珍藏版)》请在三一文库上搜索。

1、Java程序设计,Java Programming Spring, 2013,钦株兄它射儿二淑轰齿搭娶屉尝喊醚熏舆肠商芯随用腺么锚萌抽怔常绵掏课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,2/47,Contents,Why Exceptions? What are Exceptions? Handling Exceptions Creating Exception Types,馆长楚蚀草鸯刁盗巴钮四比爆汰棕之谴梅虹南藕瘪呛骚焰阿颠向揉作阂故课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,3/47,Why

2、Exceptions(异常)?,During execution(执行), programs can run into many kinds of errors; What do we do when an error occurs? Java uses exceptions to provide the error-handling capabilities for its programs.,殊根眶彻郑那奖验棉挤鳃佐儡蓉陀浮操孵测所淑搏赌潘讯蜜过雁毯逆何娜课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,4/47,Exceptions (异常),E

3、rror Class Critical(严重的) error which is not acceptable in normal application program. Exception Class Possible exception in normal application program execution; Possible to handle by programmer.,似然骗翱填芭狰呻拭会街粮邯斟宣顿鞭盯揭好陆亏作弘杀涯声爽帜疤坊溺课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,5/47,Exceptions (异常),An ex

4、ception is an event(事件) that occurs during the execution of a program that disrupts(使中断) the normal flow(流程) of instructions(指令).,行炬佐天置岂泽悉幢鸵操夕瓮冯耳时观嫁瓣瞒泥蜀傈蓄梦嫂威敬碳中枉伞课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,6/47,Exceptions (异常),Treat exception as an object . All exceptions are instances of a class

5、extended from Throwable class or its subclass. Generally, a programmer makes new exception class to extend the Exception class which is a subclass of Throwable class.,株咖辐雷姥膜信旧扇性屡炊消慕臂阳甩款览铬分犁括扦旗熄裴蹲石环莲烹课件Java程序设计方案课件Java程序设计方案,7,Exception Class 继承关系,拧楔间崩疵氰稚唱移循染汁秩棺帮裁碧湿悦宰饲氯遗囤弟滇渝麓侧呆盟交课件Java程序设计方案课件Java程序设

6、计方案,8,异常类的层次结构:,反粹累再辖鸳佛卞囱彦康弓遣一队敢挎哩遁搓龋炽毖西捐飞逞阐作捶污练课件Java程序设计方案课件Java程序设计方案,9,Classifying(分类) Java Exceptions,Unchecked Exceptions(非检查性异常) It is not required that these types of exceptions be caught or declared on a method. Runtime exceptions can be generated by methods or by the JVM itself. Errors are

7、 generated from deep within the JVM, and often indicate a truly fatal state. Checked Exceptions(检查性异常) Must either be caught by a method or declared in its signature by placing exceptions in the method signature.,害豪用号淹赢赫蔑伙幌怎捕仲甜矮朴革早于惜乐缨啄精蔡鸯兹矫祝窘嗜夸课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,10/47,Exc

8、eption的分类,非检查性异常(unchecked exception): 以RuntimeException为代表的一些类,编译时发现不了,只在能运行时才能发现。 检查性异常(checked exception): 一般程序中可预知的问题,其产生的异常可能会带来意想不到的结果,因此Java编译器要求Java程序必须捕获或声明所有的非运行时异常。 以IOException为代表的一些类。如果代码中存在检查性异常,必须进行异常处理,否则编译不能通过。如:用户连接数据库SQLException、FileNotFoundException。,称耸历仆昆疵狄厂龙郧介莉释巢膨薄秋溶丫那蜂哎楞阉鹰徐耍永

9、猪哮夷赵课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,11/47,Exception的分类,什么是Runtime Exception: Java虚拟机在运行时生成的异常,如:被0除等系统错误、数组下标超范围等,其产生比较频繁,处理麻烦,对程序可读性和运行效率影响太大。因此由系统检测, 用户可不做处理,系统将它们交给默认的异常处理程序(当然,必要时,用户可对其处理)。 Java程序异常处理的原则是: 对于Error和RuntimeException,可以在程序中进行捕获和处理,但不是必须的。 对于IOException及其他异常,必须在程序进行捕获和

10、处理。异常处理机制主要处理检查性异常。,蔼渭仗宫裂杠湍满瘦纪驳贾蘸剩抛旗瓮苯找娜嗅静泻秦绢淮餐渺洗巨洗邱课件Java程序设计方案课件Java程序设计方案,12,Java Exception Type Hierarchy(层次),virtual machine errors,领豆堰那键狸上族脸狗罗咱痊水法吗哇缘待荐售叔酿俭孵数拱浑佑赦致付课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,13/47,系统异常类的层次结构:,挤滔锡沸煤脸矣鹤痕聊棠戮疤备海撤嘲窜宿旬萝粉缓揭酪沈苞区闻媒狰固课件Java程序设计方案课件Java程序设计方案,chapter 8

11、Exceptions,14/47,Exception的分类,System-Defined Exception(系统定义的异常) Programmer-Defined Exception(程序员自定义异常),闹雹情仕永起撞抽许旨镣戎极阶桔战朗跟辖蝗勾呆撬朽硫盈厉啸滞宋哩锤课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,15/47,System-Defined Exception(系统定义的异常),Raised implicitly by system because of illegal execution of program; Created by

12、 Java System automatically; Exception extended from Error class and RuntimeException class.,亢猎篆中庞捕句最歼堤完晕莎捉入桩绸每肮思幽闰易朔妙疯辙内菌责缔早课件Java程序设计方案课件Java程序设计方案,16/47,System-Defined Exception,IndexOutOfBoundsException: When beyond the bound of index in the object which use index, such as array, string, and vect

13、or ArrayStoreException: When assign object of incorrect type to element of array NegativeArraySizeException: When using a negative size of array NullPointerException: When refer to object as a null pointer SecurityException: When violate security. Caused by security manager IllegalMonitorStateExcept

14、ion: When the thread which is not owner of monitor involves wait or notify method,碰敌篙绚纂坡钉搔妈殃榷甘紧支撅蹈皿贱帘梆桩为嘲量拣九鞋稻蒜独碎睡课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,17/47,Programmer-Defined Exception (程序员自定义异常),Exceptions raised by programmer Subclass of Exception class Check by compiler whether the exce

15、ption handler for exception occurred exists or not If there is no handler, it is error.,司蛹锑冉妄纤芦颈淋窝妈谅威虹纵洞泌篱化容恭娠尖易浸鹰鞍所友棋莉户课件Java程序设计方案课件Java程序设计方案,18/47,User-defined Exceptions(用户自定义异常),class UserErr extends Exception ,Creating Exception Types:,酉朽岂坤唉稿氨径礁署踢侧媚浇梢檬丈戮剖疑易娘炽凉预碘势坏镰繁农牢课件Java程序设计方案课件Java程序设计方案,

16、chapter 8 Exceptions,19/47,Example 1:,public class InsufficientFundsException extends Exception private BankAccount excepbank; private double excepAmount; InsufficientFundsException(Bank ba, double dAmount) excepbank=ba; excepAmount=dAmount; ,胸逐特踊豹慌簇堡滇馈汐肪胀予润孤巫板獭溢蹿蚌咏呀醚清录汇窟苑汰睡课件Java程序设计方案课件Java程序设计方案,

17、20,程序运行时发生异常,系统会抛出异常,如果程序中未处理和捕获异常,异常抛出后程序运行中断。,public class Test public int bar() int a = new int2; for (int x = 0; x = 2; x+) ax = 0; /抛出异常,程序中断 return a; public static void main(String args) Test t = new Test(); t.bar();/程序中断 System.out.println(“Method: foo”); /不被执行 ,系统给出的错误信息: Exception in threa

18、d main java.lang.ArrayIndexOutOfBoundsException: 2 at exception.Test.bar(Test.java:7) at exception.Test.main(Test.java:25),届恕染授嚼纶昨稻向梯禁妖呜坝止良桃领狡纫渺赘船鸵说鉴盆寂帚耿棘失课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,21/47,Handling Exceptions(处理异常),Throwing an exception(抛出异常) When an error occurs within a method. A

19、n exception object is created and handed off to the runtime system(运行时系统). The runtime system must find the code to handle the error. Catching an exception(捕获异常) The runtime system(运行时系统) searches for code to handle the thrown exception. It can be in the same method or in some method in the call(调用)

20、 stack(堆栈).,是交诬怜带福费杭旬齿挫知驻颤撵恫宪鹤三雹提衡剔帐翠去蛤神练煎仆山课件Java程序设计方案课件Java程序设计方案,22/47,Keywords for Java Exceptions,tryMarks the start of a block associated with a set of exception handlers. catchIf the block enclosed by the try generates an exception of this type, control moves here; watch out for implicit sub

21、sumption. finallyAlways called when the try block concludes, and after any necessary catch handler is complete. throwsDescribes the exceptions which can be raised by a method. throwRaises an exception to the first available handler in the call stack, unwinding the stack along the way.,悦杖舒诌捕怖啊棺官斡鸿畦靡务

22、何馈繁第满驴谋丸尽峻详播绅怜邪原砖雷课件Java程序设计方案课件Java程序设计方案,23/47,抛出异常 throw, throws,在一个方法的运行过程中,如果一个语句引起了错误时,含有这个语句的方法就会创建一个包含有关异常信息的异常对象,并将它传递给Java运行时系统。 我们把生成异常对象并把它提交给运行时系统的过程称为抛出(throw)异常。 throw 在方法体中用throw手工抛出异常; throws 在方法头部间接抛出异常,即:申明方法中可能抛出的异常。,萨垢刮樟勋羽仟潮痰央滨道邹赵餐根梨诽勇隅竟绘挞西钵盆粮典婿乖牌幻课件Java程序设计方案课件Java程序设计方案,24/47,

23、1. 在方法体中用throw手工抛出异常,throw抛出异常,可以是系统定义的异常,也可以是用户自定义的异常。 语法格式: 或 例如:下面语句就抛出了一个IOException异常: throw new IOException();,异常类名 对象名 new 异常类构造函数; throw 对象名;,throw new 异常类构造函数;,扎硫咱宦僵陵扰三闸谬帐陌撬墅蠢跟主谚酋浊纬晾忻辞缓扔越撂梁禾掷哈课件Java程序设计方案课件Java程序设计方案,25/47,throw Example,class ThrowStatement extends Exception public static v

24、oid exp(int ptr) try if (ptr = 0) throw new NullPointerException(); catch(NullPointerException e) public static void main(String args) int i = 0; ThrowStatement.exp(i); ,员铀美酌共堆子逸彝益窒望弗衍囤改钓均购擦滚寺汝狼奄讹瑚雌柳股牧管课件Java程序设计方案课件Java程序设计方案,26/47,2. throws间接抛出异常(申明异常),一个方法不处理它产生的异常,而是沿着调用层次向上传递,由调用它的方法来处理这些异常,叫声明

25、异常。 在定义方法时用throws关键字将方法中可能产生的异常间接抛出。 若一个方法可能引发一个异常,但它自己却没有处理,则应该声明异常,并让其调用者来处理这个异常,这时就需要用throws关键字来指明方法中可能引发的所有异常。,类型 方法名(参数列表) throws 异常列表 /代码 ,顷献胎缩糠篆档情咋控块显斗胰贯蚤钉航镇篷痉既廉捕派固祟稠锥牢饭抒课件Java程序设计方案课件Java程序设计方案,27,Example 1:,public class ExceptionTest void Proc(int sel) throws ArrayIndexOutOfBoundsException

26、System.out.println(“In Situation + sel ); if(sel=1) int iArray =new int4; iArray10=3; /抛出异常 ,吟扔平辑修园椿鳞芍花谎晕痪溅耻秉振柄思捅匪造揩痊辜钱奄衣碍构止北课件Java程序设计方案课件Java程序设计方案,28/47,异常向上传递Example,class ThrowStatement extends Exception public static void exp(int ptr) throws NullPointerException if (ptr = 0) throw new NullPoin

27、terException(); public static void main(String args) int i = 0; ThrowStatement.exp(i); ,运行结果: java.lang.NullPointerException at ThrowStatement.exp(ThrowStatement.java:4) at ThrowStatement.main(ThrowStatement.java:8),不亚坪螺思票园辩翔胺容障网鼎母乍翱皋饼阮勘网瞪醉妥鞘搪倘纠受城瓷课件Java程序设计方案课件Java程序设计方案,29,Exceptions - throwing mu

28、ltiple(多个) exceptions,A Method can throw multiple exceptions. Multiple exceptions are separated by commas after the throws keyword:,public class MyClass public int computeFileSize() throws IOException, ArithmeticException . ,效碉臆椿凳癌半肯惰惩烂玖威屑笨饺伟纸乙诞赎猿崖耽仙址傍妒天瘩秧侯课件Java程序设计方案课件Java程序设计方案,30/47,Handling Exc

29、eptions,在一个方法中,对于可能抛出的异常,处理方式有两种: 一个方法不处理它产生的异常,只在方法头部声明使用throws抛出异常,使异常沿着调用层次向上传递,由调用它的方法来处理这些异常。 用try-catch-finally语句对异常及时处理;,潦旺骗羞彤粒蚊禄镁谅卧聋缺摘成钞噶胁旭僧腺珊振堪仇猩搞润拌侥稿蔷课件Java程序设计方案课件Java程序设计方案,31,Handling Exceptions,public void replaceValue(String name, Object value) throws NoSuchAttributeException Attr att

30、r=find(name); if(attr=null) throw new NoSuchAttributeException(name); attr.setValue(value); ,try replaceValue(“att1”, “newValue”); catch(NoSuchAttributeException e) e.printStackTrace(); ,当replaceValue()方法被调用时,调用者需处理异常。,韦冈横笋处允藕烤蹿译番佐扒的私赂丙锗僚飞遍债詹及引生锐弟布棚沤俄课件Java程序设计方案课件Java程序设计方案,32,处理异常语句try-catch-final

31、ly的基本格式为:,try /可能产生异常的代码; /不能有其它语句分隔 catch(异常类名 异常对象名) / 异常处理代码; /要处理的第一种异常 catch(异常类名 异常对象名) /异常处理代码; /要处理的第二种异常 finally /最终处理(缺省处理) ,售炬仔敖铬爵置秀就投谚浸屿豆颤搂摆畴恬饱贤逸蓟冉街饮烤嘱幻页鹃苟课件Java程序设计方案课件Java程序设计方案,33,Exceptions Syntax(语法)示例,try / Code which might throw an exception / . catch(FileNotFoundException x) / co

32、de to handle a FileNotFound exception catch(IOException x) / code to handle any other I/O exceptions catch(Exception x) / Code to catch any other type of exception finally / This code is ALWAYS executed whether an exception was thrown / or not. A good place to put clean-up code. ie. close / any open

33、 files, etc. ,良衣虎淄玲撩逾粟否晕囱算拾穆梆刷杠福栏翱敲赔易爸朔靶诣调券爽密米课件Java程序设计方案课件Java程序设计方案,34,Handling Exceptions(处理异常),try-catch 或 try-catch-finally . Three statements help define how exceptions are handled: try identifies a block of statements within which an exception might be thrown; A try statement can have multip

34、le catch statements associated with it. catch must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. The statements are executed if an exception of a particular type occurs within the try block.,吧倒棉幅沿枣坐穴爹书寻短募拦启漾淫松凌长宝使遗折稼终皱惋会统郭窥课件J

35、ava程序设计方案课件Java程序设计方案,35,Handling Exceptions,finally (可选项) must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block. Even if the try and catch block have a return statement in them, finally will s

36、till run.,晰窑磺膳臆完孽痊倦争院篆格剁绑溪算啮孽锦重死胞侥驰阉浊毕皱咽乎君课件Java程序设计方案课件Java程序设计方案,36,用try-catch-finally语句对异常及时处理Example,class ThrowStatement extends Exception public static void exp(int ptr) try if (ptr = 0) throw new NullPointerException(); catch(NullPointerException e) public static void main(String args) int i

37、= 0; ThrowStatement.exp(i); ,僧声确荆烂沪麦韧倚侄晃醛屑勉芝诊叫酵食雾泻头捎喜悔号烂盈耪淳娃材课件Java程序设计方案课件Java程序设计方案,37,系统抛出异常后,捕获异常,运行finally块,程序运行继续。,public class Test public void foo() try int a = new int2; a4 = 1; /* causes a runtime exception due to the index */ System.out.println(“Method: foo”);/若异常发生,不执行 catch (ArrayIndexO

38、utOfBoundsException e) System.out.println(exception: + e.getMessage(); e.printStackTrace(); finally System.out.println(Finally block always execute!); public static void main(String args) Test t = new Test(); t.foo(); System.out.println(“Excecution after Exception!”); /继续执行 ,眼踌库人楼拙禽蹈拈逝绷锤省针掺骚镐媚乙酌芭柞裸钥

39、秦晕过障酿蹬雾恐课件Java程序设计方案课件Java程序设计方案,38,运行结果:,exception: 4 java.lang.ArrayIndexOutOfBoundsException: 4 at exception.Test.foo(Test.java:8) at exception.Test.main(Test.java:20) Finally block always execute! Excecution after Exception!,栗瘩佃傀虾据警消弛肝桩讯巍尧抠傻灼耪铅凤各他冉德舶化撒歉掺钞用遣课件Java程序设计方案课件Java程序设计方案,39,Exceptions

40、-throwing multiple exceptions,public void method1() MyClass anObject = new MyClass(); try int theSize = anOputeFileSize(); catch(ArithmeticException x) / . catch(IOException x) / . ,荣詹乙左孺茧些贝暖膝彪矩辅戏疑钨库夜昧胺荔溪负萍吩漏抓添噶株顽膊课件Java程序设计方案课件Java程序设计方案,40,Exceptions -catching multiple exceptions,Each try block ca

41、n catch multiple exceptions. Start with the most specific exceptions FileNotFoundException is a subclass of IO Exception It MUST appear before IOException in the catch list,public void method1() FileInputStream aFile; try aFile = new FileInputStream(.); int aChar = aFile.read(); /. catch(FileNotFoun

42、dException x) / . catch(IOException x) / . ,促拣穴奢腮雄掳哪殃馁惊里孜去阑捡浓扯苯封峡权翟仔诲唉晦垄吠依秘咐课件Java程序设计方案课件Java程序设计方案,41,Exception -The catch-all Handler,Since all Exception classes are a subclass of the Exception class, a catch handler which catches Exception will catch all exceptions. It must be the last in the ca

43、tch List.,public void method1() FileInputStream aFile; try aFile = new FileInputStream(.); int aChar = aFile.read(); /. catch(IOException x) / . catch(Exception x) / Catch All Exceptions ,声衬郴皆阮肖每趟脓吴焊企颧闭琉复醇虏沦立客峦胰朋纹锨蜒裁看微龟崇课件Java程序设计方案课件Java程序设计方案,42,User-defined Exceptions(用户自定义异常)的处理,class UserErr ex

44、tends Exception ,用户自定义异常是检查性异常(checked exception),必须用throw手工抛出并处理。,class UserClass UserErr x = new UserErr(); . if (val 1) throw x; ,酱肢旨薛挠汞旅储遁翼潦猜帐坚力拴琴扯符焊遣瞻区杰辞加匡乎第堆庄忍课件Java程序设计方案课件Java程序设计方案,43,/ThrowExample.java,class IllegalValueException extends Exception ,class UserTrial int val1,val2; public Use

45、rTrial(int a,int b) val1=a; val2=b; void show() throws IllegalValueException if (val10) throw new IllegalValueException(); System.out.println(“Value1=”+ val1);/不运行 System.out.println(Value2 =+val2); ,class ThrowExample public static void main(String args ) UserTrial values=new UserTrial(-1,1); try v

46、alues.show(); catch (IllegalValueException e) System.out.println(Illegal Values: Caught in main); ,输出: Illegal Values: Caught in main,帚廓归坛翟杀昂岿男步粥瓤驻杯康妮汹敌彝睬鸦帐酪喧症欢碎讣畅床妥续课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,44/47,Exception Propagation(传递),An exception can be handled at a higher level if it is n

47、ot appropriate to handle it where it occurs. Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method. A try block that contains a call to a method in which an exception is thrown can be used to catch that excepti

48、on.,揉恐笺愉廊颓凤钻滁拟氏刹丫犬崖渔全藕乡询傣懦村恋讳椭贤但贝汀虫咬课件Java程序设计方案课件Java程序设计方案,chapter 8 Exceptions,45/47,Exception Propagation (传递),Exception Propagation Order If there is no catch block to deal with the exception, it is propagated to calling method(调用方法) All executions are ignored until finding the exception handler Propagate.java,薄酒刁偿凛锣桶胀龚堵占证匡篱倔烁垄榔度歇斩膝辉气盾洲浪租部敖戮嗽课件Java程序设计方案课件Java程序设计方案,46,Exception Propagation,public class Propagate void orange() int m = 25, i = 0; i = m / i; void apple() orange(); public static void main(String args) Propagate p = new Propagate();

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

当前位置:首页 > 其他


经营许可证编号:宁ICP备18001539号-1