Java 7之异常第二篇

来源:互联网 发布:dps数据统计软件 编辑:程序博客网 时间:2024/05/17 03:06


1、异常题目01

interface Type1 {void f() throws CloneNotSupportedException;}interface Type2 {void f() throws InterruptedException;}interface Type3 extends Type1, Type2 {}/* * 每一个接口都限制了方法 f 可以抛出的被检查异常集合。 * 一个方法可以抛出的被检查异常集合是它所适用的所有类型声明要抛出的被检查异常集合的交集, * 而不是合集。因此,静态类型为 Type3 的对象上的 f 方法根本就不能抛出任何被检查异常。因此, * Test01可以毫无错误地通过编译,并且打印 Hello world。 */public class Test01 implements Type3 {public void f() {System.out.println("Hello world");}public static void main(String[] args) {Type3 t3 = new Test01();t3.f();}}
最后的输出结果为Hello world


2、异常题目2

public static void main(String[] args){int[] date1= {1,2,3,4,5,6};int[] date2= {6,1,3,5,0,3};// 下层抛出的异常由上层不捕获解决try {cal(date1,date2);} catch (Exception e) {e.printStackTrace();}}public static void cal(int[] date1,int[] date2) throws Exception{for(int i = 0; i<date1.length; i++){try{System.out.println(date1[i] + "/" + date2[i] + " = " + date1[i]/date2[i]);}catch(Exception ex){System.out.println("发生异常");throw ex;}}}
运行结果如下:

1/6 = 02/1 = 23/3 = 14/5 = 0发生异常java.lang.ArithmeticException: / by zeroat com.zyg.test.exception.TestException.cal(TestException.java:20)at com.zyg.test.exception.TestException.main(TestException.java:11)
如果不在方法cal的catch块中抛出Exception异常,则运行结果如下:

1/6 = 02/1 = 23/3 = 14/5 = 0发生异常6/3 = 2
所以说catch可以增强程序的健壮性。

3、异常题目3


public class Type3 {public static void main(String[] args) {try {} catch (Exception e) {}finally{closeException();System.out.println("执行打印操作");}}private static void closeException() {//System.exit(0);try{throw new AssertionError();}catch(Exception ex){ex.printStackTrace();}}}
如上的执行会导致finally块无法继续执行下去,因为closeException()方法抛出了异常或调用了System.exit(0);有如下的解决办法:
public class InOut {static void copy(String src, String dest) throws IOException {InputStream in = null;OutputStream out = null;try {in = new FileInputStream(src);out = new FileOutputStream(dest);byte[] buf = new byte[1024];int n;while ((n = in.read(buf)) > 0)out.write(buf, 0, n);} finally {/*if (in != null)in.close();if (out != null)out.close();*/ //对close 的调用可能会导致finally 语句块意外结束//方案1/*if (in != null) {try {in.close();} catch (IOException ex) {// There is nothing we can do if close fails}if (out != null)try {out.close();} catch (IOException ex) {// There is nothing we can do if close fails}}*///方案2closeIgnoringException(in);closeIgnoringException(out);}}private static void closeIgnoringException(Closeable c) {if (c != null) {try {c.close();} catch (IOException ex) {// There is nothing we can do if close fails}}}}

再来看一个例子:
try {if (isThrow) {throw new Exception("test3() 抛出的异常");}// 执行不到,不报错System.out.println("test3() 抛出异常以后的try内容...");   } catch (Exception e) {throw e;System.out.println("test3() catch (Exception e)"); // 执行不到,报错}finally{throw new Exception();System.out.println("test3() catch (Exception e)"); // 执行不到,报错}// 执行不到,报错System.out.println("test3() try catch 后面的内容...");
可以看出,throw会中断当前的执行逻辑,而进入下一个执行逻辑。在try、catch和finally中都一样。





























0 0
原创粉丝点击