为了正常的体验网站,请在浏览器设置里面开启Javascript功能!

异常

2011-03-30 43页 ppt 230KB 48阅读

用户头像

is_969540

暂无简介

举报
异常null异常异常异常异常异常的概念 异常的分类 捕获异常 声明异常 抛出异常 构建自己的异常 1 异常的概念1 异常的概念什么是异常? 异常实际上是程序中意外导致中断了正常的指令流的一种事件. 总有一些问题是编译时刻预计不到的 能否很好地处理运行时刻的异常情况是一个程序健康的标志 很多程序员普遍缺乏异常处理意识 用户都知道软件没有不出错的,所以要把运行错误报告给用户,而不是试图隐藏1 异常的概念1 异常的概念没有处理错误的程序: public int getInt(){ byte[] buf=new byt...
异常
null异常异常异常异常异常的概念 异常的分类 捕获异常 声明异常 抛出异常 构建自己的异常 1 异常的概念1 异常的概念什么是异常? 异常实际上是程序中意外导致中断了正常的指令流的一种事件. 总有一些问题是编译时刻预计不到的 能否很好地处理运行时刻的异常情况是一个程序健康的标志 很多程序员普遍缺乏异常处理意识 用户都知道软件没有不出错的,所以要把运行错误报告给用户,而不是试图隐藏1 异常的概念1 异常的概念没有处理错误的程序: public int getInt(){ byte[] buf=new byte[1024]; System.in.read(buf); String str=new String(buf); str=str.trim(); int i=Integer.parseInt(str); }1 异常的概念1 异常的概念使用常规方式处理异常时你会发现大部分精力花在出错处理上了. 只把能够想到的错误考虑到,对以外的情况无法处理 程序可读性差(如果要插入一个功能段) 出错返回信息量太少 1 异常的概念1 异常的概念用异常的形式处理错误 public int getInt(){ try{ byte[] buf=new byte[1024]; System.in.read(buf); String str=new String(buf); str=str.trim(); int i=Integer.parseInt(str); }catch(IOException e){ System.out.println(e); }catch(NumberFormatException e){ System.out.println(e); } }1 异常的概念1 异常的概念和传统的方法比较异常的优点: 1.把错误代码从常规代码中分离出来 2. 把错误传播给调 用堆栈 3. 按错误类型和 错误差别分组 4. 系统提供了对于一些无法预测的错误的捕获和处理 5. 克服了传统方法的错误信息有限的问题1 异常的概念1 异常的概念.class ExcepTest { public static void main(String args[]) { int b=0; int a; try { a=4/b;} catch(ArithmeticException e) { System.out.println(“divided by 0”);} } }try{ URL url=new URL(http://www.hit.edu.cn/”,”hit.gif”);} catch(MalformedURLException e) { badURL=true; repaint();}2 异常的分类2 异常的分类在Java语言中,对很多可能出现的异常进行了化,并将它们封装成了各种类,统称为异常类。一旦在程序运行过程中发生异常,Java虚拟机就会自动地创建一个相应的异常类对象,并将该对象作为参数抛给处理异常的方法。 异常是一个类,它继承自Throwable类,所有的Throwable类的子孙类所产生的对象都是例外(包括异常和错误). Error类:由Java虚拟机生成并抛出,Java程序不做处理. RuntimeException类(被0除等系统错误,数组下标超范围):由系统检测, 用户的Java 程序可不做处理,系统将它们交给缺省的异常处理程序. Exception类(程序中的问题,可预知的): Java编译器要求Java程序必须捕获或声明所有的非运行时异常 throw关键字:用户自己产生异常 2 异常的分类2 异常的分类.缺省的异常 处理程序 要处理2 异常的分类2 异常的分类2 异常的分类2 异常的分类ArrayIndexOutOfBandsException IOException FileNotFoundException MalformedURLException NumberFormatException OutOfMemoryException如果在使用能够产生异常的方法而没有捕获和处理,或者声明,将不能通过编译 3 捕获异常3 捕获异常捕获并处理异常 try { //接受监视的程序块,在此区域内发生 //的异常,由catch中指定的程序处理; }catch(要处理的异常种类和标识符) { //处理异常; }catch(要处理的异常种类和标识符) { //处理异常; }3 捕获异常3 捕获异常Exception是与编程有关的所有异常类的基类,没有太多的具体信息,不过可以调用它从其基类Throwable继承的方法 String getMessage() String getLocalizedMessage() String toString() Void printStackTrace() Void printStackTrace(PrintStream) Void printStackTrace(java.io.PrintWriter) Throwable fillinStackTrace()3 捕获异常3 捕获异常例:编写Java程序,包含三种异常 算术异常, 字符串越界,数组越界 观察输出信息: 每个异常对象可以直接给出信息 3 捕获异常3 捕获异常class first_exception { public static void main(String args[]) {char c; int a,b=0;int[] array=new int[7]; String s="Hello";try {a=1/b;} catch(ArithmeticException ae) { System.out.println("Catch"+ae);}try {array[8]=0;} catch(ArrayIndexOutOfBoundsException ai) { System.out.println("Catch" +ai);} try{ c=s.charAt(8);} catch(StringIndexOutOfBoundsException se) { System.out.println("Catch "+se);} }}3 捕获异常3 捕获异常一定会执行的程序块---finally 异常处理的统一出口 try { //常规的代码; } catch() { //处理异常 } finally { //不论发生什么异常(或者不发生任何异常),都要执行的部分; }3 捕获异常3 捕获异常finally在文件处理时非常有用 try { 对文件进行处理的程序; }catch(IOException e) { //对文件异常进行处理; }finally { 不论是否发生异常,都关闭文件; }3 捕获异常3 捕获异常class ThreeException extends Exception {} public class FinallyWorks { static int count = 0; public static void main(String[] args) { while(true) { try { // Post-increment is zero first time: if(count++ == 0) throw new ThreeException(); System.out.println("No exception"); } catch(ThreeException e) { System.err.println("ThreeException"); } finally { System.err.println("In finally clause"); if(count == 2) break; // out of "while" } } } } ///:~ 3 捕获异常3 捕获异常重新抛出异常 catch(Exception e){ System.out.println(“An exception was thrown”); throw e; } Rethrowing an exception causes it to go to the exception handlers in the next-higher context. Any further catch clauses for the same try block are still ignored. 3 捕获异常3 捕获异常public class Rethrowing { public static void f() throws Exception { System.out.println("originating the exception in f()"); throw new Exception("thrown from f()"); } public static void g() throws Throwable { try { f(); } catch(Exception e) { System.err.println("Inside g(),e.printStackTrace()"); e.printStackTrace(); throw e; // 17 // throw e.fillInStackTrace(); // 18 } } 3 捕获异常3 捕获异常public static void main(String[] args) throws Throwable { try { g(); } catch(Exception e) { System.err.println( "Caught in main, e.printStackTrace()"); e.printStackTrace(); } } } ///:~ 4 声明异常4 声明异常一个方法不处理它产生的异常,而是沿着调用层次向上传递,由调用它的方法来处理这些异常,叫声明异常. 声明异常的方法 在产生异常的方法名后面加上要抛出(throws)的异常的列 void compute(int x)throws ArithmeticException {…} returnType methodName([parameter list]) throws exceptionListnull例:若因某种原因不想在操作的方法中处理异常 public method1() { int x; try { x=System.in.read(); compute(x);} catch(IOException ioe) { System.out.println(“read error”); } catch(ArithmeticException e) { System.out.println(“devided by 0”); } }public int compute(int x) throws ArithmeticException { return z=100/x;}nullnull例:说出程序执行结果 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; }else if(sel==1) {int iArray[]=new int[4]; iArray[10]=3; } } null抛出异常: 不是系统意外产生,而是人为地抛出 throw ThrowableObject; throw new ArithmeticException(); 例:编写程序人为抛出(JavaThrow.java) ArithmeticException, ArrayIndexOutOfBoundsException StringIndexOutOfBoundsExceptionA methodExceptionAnother methodthrowcaught13.5 抛出异常13.5 抛出异常class JavaThrow { public static void main(String args[]) {try{ throw new ArithmeticException();} catch(ArithmeticException ae) { System.out.println(ae); }try{ throw new ArrayIndexOutOfBoundsException();} catch(ArrayIndexOutOfBoundsException ai) { System.out.println(ai); } try { throw new StringIndexOutOfBoundsException();} catch(StringIndexOutOfBoundsException si){ { System.out.println(si); }13.6 创造自己的异常13.6 创造自己的异常不是由Java系统监测到的异常(下标越界,被0-除等),而是由用户自己定义的异常. 用户定义的异常同样要用try--catch捕获,但必须由用户自己抛出 throw new MyException. 异常是一个类,用户定义的异常必须继承自Throwable或Exception类,建议用Exception类. 13.6 创造自己的异常13.6 创造自己的异常形如: class MyException extends Exception {….}; 例1 :计算两个数之和,当任意一个数超出范围时,抛出自己的异常 public class NumberRangeException extends Exception { public NumberRangeException(String msg) { super(msg); } }13.6 创造自己的异常13.6 创造自己的异常. public boolean action() { try { int answer = CalcAnswer(10, 20); answerStr = String.valueOf(answer); }catch (NumberRangeException e) { answerStr = e.getMessage(); } return true; } 13.6 创造自己的异常13.6 创造自己的异常public int CalcAnswer(int n1, int n2) throws NumberRangeException { int answer = 0; if ((int1 < 10) || (int1 > 20) || (int2 < 10) || (int2 > 20)) { NumberRangeException e = new NumberRangeException (”Numbers not within the specified range."); throw e; } answer = int1 + int2; return answer; }13.6 创造自己的异常13.6 创造自己的异常例2 :在定义银行类时,若取钱数大于余额则作为异常处理(InsufficientFundsException). 思路:产生异常的条件是余额少于取额, 因此是否抛出异常要判断条件 取钱是withdrawal方法中定义的动作,因此在该方法中产生异常. 处理异常安排在调用withdrawal的时候,因此withdrawal方法要声明异常,由上级方法调用 要定义好自己的异常类 13.6 创造自己的异常13.6 创造自己的异常class Bank { private double balance; public Bank(int ba){ this.balance = ba; } public void deposite(double dAmount) { if (dAmount > 0.0) { balance += dAmount; } } public void withdrawal(double dAmount) throws InsufficientFundsException { if (balance < dAmount) { throw new InsufficientFundsException(this, dAmount); } balance = balance - dAmount; } public String show_balance() { return new String("The balance is " + (int) balance); } } 13.6 创造自己的异常13.6 创造自己的异常 public class ExceptionDemo { public static void main(String args[]) { Bank ba = new Bank(50); try { ba.withdrawal(100); System.out.println("Withdrawal successful!"); } catch (InsufficientFundsException e) { e.printStackTrace(); System.out.println(e.excepMessage()); } } }13.6 创造自己的异常13.6 创造自己的异常class InsufficientFundsException extends Exception { private Bank excepbank; private double excepAmount; InsufficientFundsException(Bank ba, double dAmount) { excepbank = ba; excepAmount = dAmount; } public String excepMessage() { String str = excepbank.show_balance()+"\n" + "The withdrawal was " + excepAmount; return str; } }13.7 小结13.7 小结1.一般:正常程序和出错处理分离开来 try { Java statement; }catch(ExceptionType1 ExceptionObject) { Exception1 handling; } catch(ExceptionType2 ExceptionObject) { Exception2 handling; }…. }finally { final handling; // (统一的出口,最终必定要执行) }} 13.7 小结13.7 小结2.把异常传播给堆栈,沿着被调用的顺序往前寻找,只要找到符合该异常种类彻底异常处理程序,就交给这部分程序去处理13.7 小结13.7 小结3.异常可以人为地抛出,用throw new 语句 4.异常可以是系统已经定义好的,也可以是用户自己定义的 5.用户自己定义的异常一定继承自Throwable或Exception类练习练习程序产生并处理以下异常 NumberFormatException ArrayIndexOutOfBoundsException ClassCastException 创建对象数组。在对其操作时抛出 NullPointerException附加附加1.编写一个程序,允许用户向一个大小为10的数组输入整型值。程序应通过索引,或者通过指定一个大于0的值来查找数组元素,从而获得数组中的值。程序应处理任何在向数组输入数值或访问数组元素时发生的异常。此外,程序应使用自定义一个NumberNotFoundException异常处理类。 如果试图访问超出数组边界的元素,则捕获ArrayIndexOutOfBoundsException异常,并显示一个合适的错误消息。 2.修改2的程序,创建一个名为DuplicateValueException的异常类,以检测用户是否输入了重复的数。如果用户输入的数已经存在于数组中,则应该抛出一个DuplicateValueException异常。此外,还要显示一个合适的错误信息。在处理完异常后,程序应该能够继续正常的执行。 3.定义一个InvalidInputException类。该类应是Exception的直接子类。 它应指定默认消息“Your input was invalid”,但允许程序员也能够指定某个定制的消息。 null4. 定义一个ExceptionTest类。ExceptionTest类不仅要检测除数是否为0和是否为有效的整数输入,还要确保输入的整数为正数。如果不是,则应该抛出一个InvalidInputException异常,并显示消息“You must enter positive number”。程序应该捕获该异常,并显示一个错误消息。 5.从键盘读入一行信息,根据读入的内容来判定是否发生了异常。如果读入的是空串,则抛出EmptyStringException异常;如果读入的内容中包含有数字,则抛出IncludeNumberException异常。提示:程序中用到String的indexOf()方法,它返回所指定的字符在字符串中第一次出现的位置。如果这个位置大于等于0,表名字符串中含有该字符。程序中使用循环来查找是否出现0到9这10个数字。联系方式联系方式杭州和盈科技公司 Address:潮王路238号银地大厦2F www.aowin.com
/
本文档为【异常】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。

历史搜索

    清空历史搜索