4 class Circle implements Figure interface Figure double
4、接口方法 class Circle implements Figure { interface Figure { Ø 无修饰 double half=0. 5, pi=3. 14159; double x, y, r; Circle(double u, double v, double m) void parameter(); Ø 但在实现接口方法的类中,修饰符为public { x=u; y=v; r=m; } void area(); public void parameter() } { System. out. println(x+“ “+y+“ “+r); } class Triangle implements Figure { double b, h; Triangle (double u, double v) { b = u; h = v; } public void parameter() { System. out. println(b + “ “ + h); } public void area() { System. out. println(half*h*b); } } public void area() { System. out. println(pi*r*r); } } Triangle t = new Triangle(2, 3); Circle c = new Circle(4, 5, 6); Figure[] f = {t, c}; for (int i =0; i < f. length; i++) { f[i]. parameter(); f[i]. area(); 7 }
什么是异常? • 在运行时发生的错误 异常情况 public class Exception. Raised { public Exception. Raised() { } 异常 public int calculate( int operand 1, int operand 2) { int result = operand 1 / operand 2; return result; 程序突然终止并将控制交 } 给操作系统 public static void main(String[] args) { Exception. Raised obj = new Exception. Raised(); int result = obj. calculate(9, 0); System. out. println(result); } }
异常类的层次结构 Object • Throwable 具有两个子类,它们是 – Exception:处理用户程序应当捕获的异常情况 Throwable – Error:Error 类的异常为内部错误,因此在正常情况下 Error 不期望用户的程序捕获它们 SQLException AWTError Thread. Death Exception Runtime. Exception … Arithmetic. Exception Null. Pointer. Exception Number. Format. Exception … 27
Java异常类 异常 说明 Exception 异常层次结构的根类 Runtime. Exception 许多 java. lang 异常的基类 Arithmetic. Exception 算术错误情形,如以零作除数 Illegal. Argument. Exception 方法接收到非法参数 Array. Index. Out. Of. Bound. Exception 数组大小小于或大于实际的数组大小 Null. Pointer. Exception 尝试访问 null 对象成员 Class. Not. Found. Exception IOException 不能加载所需的类 数字转化格式异常,比如字符串到 float 型数字的转换无效 I/O 异常的根类 File. Not. Found. Exception 找不到文件 EOFException 文件结束 Interrupted. Exception 线程中断 Number. Format. Exception
3、finally
2. 3、finally 块 try、catch 和 finally 块的执行流程 try 块 异常 catch 块 finally 块 无异常
2. 3、finally
练习 1、关于try. . . catch. . . finally结构,描述正确的是哪项?_____ A. 必须包含多个catch B. 只能有一个catch C. finally必须有 D. 可以没有catch 2、运行下面程序时,会产生什么异常?_____。 public class X 7_1_4 { public static void main(String[] args) { int x = 0; int y = 5/x; int[] z = {1, 2, 3, 4}; int p = z[4]; } } A. Arithmetic. Exception B. Number. Format. Exception C. Array. Index. Out. Of. Bounds. Exception D. IOException
- Slides: 40