6.Java基础_异常处理绪论.ppt

任何一种程序设计语言设计的程序在运行时都有可能出现错误,例如除数为0,数组下标越界,要读写的文件不存在等等。 捕获错误最理想的是在编译期间,但有的错误只有在运行时才会发生。 对于这些错误,一般有两种解决方法: 遇到错误就终止程序的运行。 由程序员在编写程序时,就考虑到错误的检测、错误消息的提示,以及错误的处理。 Java程序运行过程中所发生的异常事件可分为两类: Error: JVM系统内部错误、资源耗尽等严重情况 Exception: 其它因编程错误或偶然的外在因素导致的一般性问题,例如: 空指针访问 试图读取不存在的文件 网络连接中断 public class Test8_1{ public static void main(String[] args) { String friends[]={lisa,bily,kessy}; for(int i=0;i5;i++) { System.out.println(friends[i]); //friends[4]? } System.out.println(\nthis is the end); } } public class NullRef{ int i=1; public static void main(String[] args) { NullRef t=new NullRef(); t=null; System.out.println(t.i); } } public class DivideZero{ int x; public static void main(String[] args) { int y; DivideZero c=new DivideZero(); y=3/c.x; System.out.println(“program ends ok!”); } } RuntimeException 错误的类型转换 数组下标越界 空指针访问 IOExeption 从一个不存在的文件中读取数据 越过文件结尾继续读取 连接一个不存在的URL Java异常处理:Java采用异常处理机制,将异常处理的程序代码集中在一起,与正常的程序代码分开,使得程序简洁,并易于维护。 Java提供的是异常处理的抓抛模型。 Java程序的执行过程中如出现异常,会自动生成一个异常类对象,该异常对象将被提交给Java运行时系统,这个过程称为抛出(throw)异常。 如果一个方法内抛出异常,该异常会被抛到调用方法中。如果异常没有在调用方法中处理,它继续被抛给这个调用方法的调用者。这个过程将一直继续下去,直到异常被处理。这一过程称为捕获(catch)异常。 如果一个异常回到main()方法,并且main()也不处理,则程序运行终止。 程序员通常只能处理Exception,而对Error无能为力。 异常处理是通过try-catch-finally语句实现的。 try { ...... //可能产生异常的代码 } catch( ExceptionName1 e ) { ...... //当产生ExceptionName1型异常时的处置措施 } catch( ExceptionName2 e ) { ...... //当产生ExceptionName2型异常时的处置措施 } [ finally{ ...... //无条件执行的语句 } ] public class Test8_2{ public static void main(String[] args) { String friends[]={lisa,bily,kessy}; try { for(int i=0;i5;i++) { System.out.println(friends[i]); } } catch(ArrayIndexOutOfBoundsException e) { System.out.println(index err); } System.out.println(\nthis is the end); } } public class DivideZero1{ int x; pub

文档评论(0)

1亿VIP精品文档

相关文档