- 2
- 0
- 约1.01万字
- 约 44页
- 2018-01-03 发布于湖北
- 举报
课件第7讲 异常
example }catch( ArithmeticException e ){ System.out.println(Catch +e); }catch( ArrayIndexOutOfBoundsException e ){ System.out.println(Catch +e.getMessage()); }catch( Exception e ){ System.out.println(Will not be executed); }finally{ System.out.println(in Proc finally); } } public static void main( String args[] ){ Proc( 0 ); Proc( 1 ); Proc( 2 ); } } 程序运行结果: ----- In Situation0 ----- no Exception caught in Proc finally ----- In Situation1 ----- Catch java.lang.ArithmeticException: / by zero in Proc finally ----- In Situation2 ----- Catch 10 in Proc finally * 声明异常 一个方法不处理它产生的异常,而是沿着调用堆栈向上传递,由调用它的方法来处理这些异常,则需要声明异常。 声明异常的方法: returnType methodName([paramlist]) throws exceptionList 例如: void compute(int x) throws ArithmeticException{ … } * example public class ThrowsException1{ static void Proc(int sel) throws 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; } } * example public static void main(String args[]){ try{ Proc(0); Proc(1); }catch(ArrayIndexOutOfBoundsException e){ System.out.println(Catch +e); }finally{ System.out.println(in Proc finally); } } } 程序运行结果: ----- In Situation0 ----- no Exception caught ----- In Situation1 ----- Catch java.lang.ArrayIndexOutOfBoundsException:10 in Proc finally * 创建自己的异常类 Java语言中允许用户定义自己的异常类,这些用户自定义异常类必须是Throwable的直接子类或间接子类。 根据Java异常类的继承关系,用户最好将自己的异常类定义为Exception的子类,而不要将其定义为RuntimeException的子类。因为对于RuntimeException的子类而言,即使调用者不进行处理,编译程序也不会报错。将自定义异常类定义为Exception的子类,可以确保调用者对其进行处理。 * example class MyException extends Exception{ private int detail; MyException( int a ){ detail = a; } public String toString( ){ return MyException +detail; } } * examp
原创力文档

文档评论(0)