




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Java程序设计,Java Programming Spring, 2009,chapter 8 Exceptions,2/25,Contents,Why Exceptions? What are Exceptions? Handling Exceptions Creating Exception Types,chapter 8 Exceptions,3/25,Why Exceptions?,During execution, programs can run into many kinds of errors; What do we do when an error occurs? Java
2、 uses exceptions to provide the error-handling capabilities for its programs.,chapter 8 Exceptions,4/25,Exceptions,Error Class Critical error which is not acceptable in normal application program. Exception Class Possible exception in normal application program execution; Possible to handle by progr
3、ammer.,chapter 8 Exceptions,5/25,Exceptions,An exception is an event that occurs during the execution of a program that disrupts(使中断) the normal flow of instructions. Treat exception as an object All exceptions are instances of a class extended from Throwable class or its subclass. Generally, a prog
4、rammer makes new exception class to extend the Exception class which is a subclass of Throwable class.,6,7,异常类的层次结构:,8,Classifying Java Exceptions,Unchecked ExceptionsIt is not required that these types of exceptions be caught or declared on a method. Runtime exceptions can be generated by methods o
5、r by the JVM itself. Errors are generated from deep within the JVM, and often indicate a truly fatal state.,Checked ExceptionsMust either be caught by a method or declared in its signature by placing exceptions in the method signature.,chapter 8 Exceptions,9/25,Exception的分类,检查性异常(checked exception):
6、 一般程序中可预知的问题,其产生的例外可能会带来意想不到的结果,因此Java编译器要求Java程序必须捕获或声明所有的非运行时异常。以IOException为代表的一些类。如果代码中存在检查性异常,必须进行异常处理,否则编译不能通过。如:用户连接数据库SQLException、FileNotFoundException。 非检查性异常(unchecked exception): 以RuntimeException为代表的一些类,编译时发现不了,只在能运行时才能发现。,chapter 8 Exceptions,10/25,Exception的分类,Runtime Exception: Java虚
7、拟机在运行时生成的例外,如被0除等系统错误、数组下标超范围等,其产生比较频繁,处理麻烦,对程序可读性和运行效率影响太大。因此由系统检测, 用户可不做处理,系统将它们交给缺省的异常处理程序(当然,必要时,用户可对其处理)。 Java程序异常处理的原则是: 对于Error和RuntimeException,可以在程序中进行捕获和处理,但不是必须的。 对于IOException及其他异常,必须在程序进行捕获和处理。异常处理机制主要处理检查性异常。,chapter 8 Exceptions,11/25,异常类的层次结构:,chapter 8 Exceptions,12/25,System-Define
8、d Exception(系统定义的异常),Raised implicitly by system because of illegal execution of program; When cannot continue program execution any more; Created by Java System automatically; Exception extended from Error class and RuntimeException class.,13/25,System-Defined Exception,IndexOutOfBoundsException :
9、When beyond the bound of index in the object which use index, such as array, string, and vector 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 pointe
10、r SecurityException : When violate security. Caused by security manager IllegalMonitorStateException : When the thread which is not owner of monitor involves wait or notify method,14,Programmer-Defined Exception,Exceptions raised by programmer Check by compiler whether the exception handler for exce
11、ption occurred exists or not If there is no handler, it is error Sub class of Exception class,chapter 8 Exceptions,15/25,Handling Exceptions,Throwing an exception When an error occurs within a method. An exception object is created and handed off to the runtime system. The runtime system must find t
12、he code to handle the error. Catching an exception The system searches for code to handle the thrown exception. It can be in the same method or in some method in the call stack.,chapter 8 Exceptions,16/25,Keywords for Java Exceptions,throwsDescribes the exceptions which can be raised by a method. th
13、rowRaises an exception to the first available handler in the call stack, unwinding the stack along the way. 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
14、 subsumption. finallyAlways called when the try block concludes, and after any necessary catch handler is complete.,17,Exception Occurrence,throws Statement When programmer-defined exception is raised, if there is no exception handler, need to describe it in the declaration part of method Exception1
15、.java,modifiers returntype methodName(params) throws e1, . ,ek ,18,Example,public class exception1 void Proc(int sel) throws ArithmeticException,ArrayIndexOutOfBoundsException System.out.println(“In Situation + sel ); if(sel=0) System.out.println(no Exception caught); return; if(sel=1) int iArray=ne
16、w int4; iArray10=3; ,19,Exception Occurrence,Raised implicitly by system Raised explicitly by programmer throw Statement ThrowStatement.java,throw ThrowableObject;,Throwable class or its sub class,20,Exception OccurrenceExample,class ThrowStatement extends Exception public static void exp(int ptr) i
17、f (ptr = 0) throw new NullPointerException(); 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),21,Throwing Exceptions,You can throw exceptions from y
18、our own methods To throw an exception, create an instance of the exception class and throw it. If you throw checked exceptions, you must indicate which exceptions your method throws by using the throws keyword,public void withdraw(float anAmount) throws InsufficientFundsException if(anAmountbalance)
19、 throw new InsuffientFundsException(Not enough cash); balance = balance - anAmount; ,22,Exceptions Syntax(语法),try / Code which might throw an exception / . catch(FileNotFoundException x) / code to handle a FileNotFound exception catch(IOException x) / code to handle any other I/O exceptions catch(Ex
20、ception 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 files, etc. ,23,该语句的基本格式为:,try 可能产生异常的代码; /不能有其它语句分隔 catch(异常类名 异常对象名) 异常处理代码; /要处理的第一种异常 catch(异常类名 异常对象名)
21、异常处理代码; /要处理的第二种异常 finally 最终处理(缺省处理) ,24/25,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; catch must be associated with a try statement and identifies a blo
22、ck 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. A try statement can have multiple catch statements associated with it.,chapter 8 Exceptions,25/25,Handling Exceptions,finally must be associa
23、ted 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 still run.,26,Exceptions -Defining checked exceptions,Any code which throws
24、 a checked exception MUST be placed within a try block. Checked exceptions are defined using the throws keyword in the method definition:,public class PrintReader extends Reader public int read() throws IOException . ,public void method1() PrintReader aReader; . initialize reader . try int theCharac
25、ter = aReader.read(); catch(IOException x) . ,27,Handling Exceptions,public void replaceValue(String name, Object value) throws NoSuchAttributeException Attr attr=find(name); if(attr=null) throw new NoSuchAttributeException(name); attr.setValue(value); try replaceValue(“att1”, “newValue”); catch(NoS
26、uchAttributeException e) e.printStackTrace(); ,28,Exceptions -throwing multiple 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 . ,29,Exc
27、eptions -throwing multiple exceptions,public void method1() MyClass anObject = new MyClass(); try int theSize = anOputeFileSize(); catch(ArithmeticException x) / . catch(IOException x) / .,30,Exceptions -catching multiple exceptions,Each try block can catch multiple exceptions. Start with the most s
28、pecific 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(FileNotFoundException x) / . catch(IOException x) / . ,31,Exc
29、eption -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 catch List,public void method1() FileInputStream aFile; try aFile = new FileInputStream(.); int aChar = aFile
30、.read(); /. catch(IOException x) / . catch(Exception x) / Catch All Exceptions ,32,Example with try-catch-finally,/* class example FileIn.java */ /* assumes each char is one byte - dangerous import java.io.*; public class FileIn public static void main(String args) try FileInputStream fin = new File
31、InputStream(“c:javatest.java”); int input; while (input = fin.read()!= -1) System.out.print(char)input); catch(IOException ie) System.out.println(e); finally fin.close(); ,chapter 8 Exceptions,33/25,User-defined Exceptions,class UserClass UserErr x = new UserErr(); / . if (val 1) throw x; ,class Use
32、rErr extends Exception ,Creating Exception Types:,chapter 8 Exceptions,34/25,Example 1,public class InsufficientFundsException extends Exception private Bank excepbank; private double excepAmount; InsufficientFundsException(Bank ba, double dAmount) excepbank=ba; excepAmount=dAmount; ,35/25,class Ban
33、k double balance; Bank(double dAmount) balance= dAmount; public void deposite(double dAmount) if(dAmount0.0) balance+=dAmount; public void withdrawal(double dAmount) throws InsufficientFundsException if (balancedAmount) throw new InsufficientFundsException(this,dAmount); balance=balance-dAmount; pub
34、lic String show_balance() String str=The balance is +(int)balance; System.out.println(str); return str; ,36,Example 1,public class ExceptionDemo public static void main(String args) try Bank ba=new Bank(50); ba.withdrawal(100); System.out.println(“Withdrawal successful!”); catch(InsufficientFundsExc
35、eption e) System.out.println(e.toString(); System.out.println(e.excepMessage(); ,37,/Example 2*ThrowExample.java*,class IllegalValueException extends Exception ,class UserTrial int val1,val2; public UserTrial(int a,int b) val1=a; val2=b; void show() throws IllegalValueException if (val10) throw new
36、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 values.show(); catch (IllegalValueException e) System.out.println(Illegal Values: Caught in main); ,chapter 8
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 二零二五年度时尚品牌广告牌匾定制安装合同
- 2025年智慧社区电气安装工程服务协议
- 2025版彩钢结构工程安装与维护合同
- 二零二五年度房产买卖合同见证书及房产抵押贷款服务
- 二零二五年度父母子女间财产分配与继承合同
- 二零二五年度苗木种植与生态园林景观绿化工程劳务分包合同
- 2025版股权投资担保与担保合同
- 二零二五年度冷链陆上货物运输托运合同新鲜直达
- 二零二五年度定制化贷款购销合同模板:个性化服务指南
- 2025年装配钳工(初级)钳工环保考试试卷
- 造口周围皮肤护理新进展
- 开题报告:拆装式自走式单轨道山地果园运输机设计
- 零碳园区解决方案
- 维修工岗位考试题及答案
- 关于新时代辽宁省国家大学科技园建设发展思路及模式的建议
- DBJ04-T495-2025 《发震断裂区域建筑抗震设计标准》
- 就业见习基地管理制度
- 2025叉车理论考试试题及答案
- T/CCAA 88-2024检验检测机构数字化应用指南
- 2025年广西公需科目答案03
- 矿井托管运营方案(3篇)
评论
0/150
提交评论