java程序中的异常处理概要1.ppt

  1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
java程序中的异常处理概要1

例1:用户自定义异常。下面代码定义一个异常类,用于表示超时异常。 class TimeOutException extends Exception { private String reason; private String ip; private int port; public TimeOutException(String s, String serverIP, int serverPort) { reason=s; ip = serverIP; port = serverPort; } public String getReason() { return reason; } public String getIp() { return ip; } public int getPort() { return port; } public String toString() { return Exception:ip is +ip+port is +port+ the reason is +reason ; } } 定义好异常类后,程序中就可以抛出、捕获并处理该类型的异常 public class ExceptionTest { public static void main(String[] args) { try { throw new TimeOutException(”Connect time out”,”166.111.8.28”,80); } catch(TimeOutException e) { System.out.println(e); } } } 例2:系统自动抛出异常。 public class a { public static void main(String[] args) { int i; int [ ] array={21,33,52,44,98}; try { while(true) { i=(int)(Math.random()*10); System.out.println(”下标为”+i+”的数组元素是”+array[i]); } } catch(ArrayIndexOutOfBoundsException e) { System.out.println(”出现数组下标越界异常”); } } } 系统自动抛出异常。 public class a { public static void main(String[] args) { int [ ] array={21,33,52,44,98}; try { System.out.println(array[6]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(”出现数组下标越界异常”); } } } (2)直接抛出异常(throw语句) 适用于用户自定义异常 格式: 生成异常类的实例e; throw e; 或: throw new 异常类构造方法 例3: 直接抛出异常。 public class ThrowException { public static void main(String[] args) { try { throw new ArithmeticException(); } catch (ArithmeticException e) {System.out.println(e);} try { throw new ArrayIndexOutOfBoundsException();} catch (ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println(throw an exception); } } (3)间接抛出异常(throws) 也称为异常转移 异常总是发生在方法执行过程中。 当方法代码不对异常处理时,异常会向方法外转移。 系统定义的异常自动向外转移。 用户自定义的异常要转移需要在方法头声明一下 (4)检查型异常处理 (5)运行时异常 运行时异常都继承自RuntimeException类 public

文档评论(0)

yaocen + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档