package Exception; public class ExceptionTest { static int[] arr = new int[5]; // 只针对异常情况才使用异常,不应该用于正常的控制流 // 创建、抛出和捕获异常的开销是很昂贵的 // 两份代码的作用都是遍历arr数组,并设置数组中每一个元素的值为0。代码1的是通过异常来终止,看起来非常难懂,代码2是通过数组边界来终止。 // 避免使用代码1这种方式 通过异常遍历的速度比普通方式遍历数组慢很多! // 参考http://www.cnblogs.com/skywang12345/p/3544287.html public static void main(String[] args) { ExceptionTest.code1(); // ExceptionTest.code2(); // ExceptionTest.result(); } public static void code2() { // 代码2 for (int i = 0; i < arr.length; i++) { arr[i] = 0; } } public static void code1() { // 代码1 try { int i = 0; while (true) { arr[i] = 0; i++; } } catch (IndexOutOfBoundsException e) { e.printStackTrace(); //异常转译(exception translation)--- 处理不好会让人困惑,而且也"污染"了高层API throw new NullPointerException(); } } public static void result() { for (int a : arr) { System.out.println(a); } } }
参考:
http://www.cnblogs.com/skywang12345/p/3544168.html
http://www.cnblogs.com/skywang12345/p/3544287.html
public static void main(String[] args) { // 在一个 try-finally 语句中,finally 语句块总是在控制权离开 try 语句块时执行的。无论 try 语句块是正常结束的,还是意外结束的, 情况都是如此。 System.out.println(decision()); //println 方法没有声明会抛出任何 被检查异常,而IOException 却正是一个被检查异常 //如果一个catch 子句要捕获一个类型为 E 的被检查异常, 而其相对应的 try 子句不能抛出 E 的某种子类型的异常,那么这就是一个编译期错误。 try { System.out.println("Hello world"); } catch (Exception e) { System.out.println("I've never seen println fail!"); } //捕获 Exception 或 Throwble 的 catch 子句是合法的,不管与其相对应的 try 子句的内容为何 try { } catch (Exception e) { System.out.println("This can't happen"); } } private static boolean decision() { try { return true; } finally { return false; } }
参考: http://www.cnblogs.com/skywang12345/p/3544353.html