java_base3_exception_AuKXzSvWN6nX.ppt

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

第5课 异常处理 Java异常处理机制 把各种不同类型的异常情况进行分类,用Java类来表示异常情况,这种类被称为异常类。把异常情况表示成异常类,可以充分发挥类的可扩展和可重用的优势。 异常流程的代码和正常流程的代码分离,提高了程序的可读性,简化了程序的结构。 可以灵活的处理异常,如果当前方法有能力处理异常,就捕获并处理它,否则只需抛出异常,由方法调用者来处理它。 异常处理 在Java编程语言中,用try和catch语句来处理异常。格式如下: 1. try { 2. // code that might throw a particular exception 3. } catch (SpecialException e) { 4. // code to execute if a SpecialException is thrown 5. } catch (Exception e) { 6. // code to execute if a general Exception exception is thrown 7. } 异常处理 如果一个方法不想处理异常,可以通过throws 语句将异常抛向上级调用方法。 int method1(int x)throws Exception1,Exception2 { if(x0)throw new Exception1(); if(x==0)throw new Exception2(); return ++x; } void method2() throws Exception1,Exception2 { //以下代码可能抛出异常 int a=method1(1); } 异常处理采用堆栈机制 public class ExTester{ static int method1(int x)throws Exception{ if(x0)throw new Exception(x0); return ++x; } static int method2(int x)throws Exception{ return method1(x); } public static void main(String args[])throws Exception{ System.out.println(method2(-1)); } } finally语句 finally语句定义一个总是被执行的代码块,而不管有没有出现异常。 finally语句 finally语句定义一个总是被执行的代码块,而不考虑是否出现异常。 异常处理流程 try{ code1; //可能抛出各种异常 }catch(SQLException e){ System.out.println(SQLException); }catch(IOException e){ System.out.println(IOException); }catch(Exception e){ System.out.println(Exception); } 异常处理流程 finally语句不被执行的唯一情况是程序先执行了终止程序的System.exit()方法 public static void main(String args[]){ try{ System.out.println(Begin); System.exit(0); }finally{ System.out.println(Finally); } System.out.println(End); } 异常处理流程 public static void main(String args[])throws Exception{ try{ System.out.println(Begin); new Sample().method1(-1); //出现SpecialException异常 System.exit(0); }catch(Exception e){ System.out.println(Wrong); throw e; //如果把此行注释掉,将得到不同的运行结果 }finally{ System.out.println(Finally); } System.out.println(End); } 异常处理流程 public static int method1(int x){ try{ if(x0)thro

您可能关注的文档

文档评论(0)

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

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

1亿VIP精品文档

相关文档