@lemonguge
2017-09-15T02:40:15.000000Z
字数 8595
阅读 374
JAVA
异常就是Java通过面向对象的思想将问题封装成了对象。
以前正常流程代码和问题处理代码相结合,使用异常能将正常流程代码和问题处理代码分离,降低了代码的复杂度,提高阅读性。
在Java中用异常类对问题进行描述,不同的问题用不同的类进行具体的描述。问题很多,意味着描述的类也很多,将其共性进行向上抽取,从而形成了异常体系。在之前介绍的继承中,我们应该知道学习体系中顶层的类可以了解该体系的基本功能,创建体系中的最子类对象,完成功能的使用。
Throwable(可抛出的)这个Java类被用来表示任何可以作为异常被抛出的类。
Throwable这个类又有两个子类:Error和Exception。无论是错误,还是异常,当问题发生就应该可以抛出,让调用者知道并处理。
Error用来表示编译时和系统错误,是由JVM抛出的严重性的问题。这种问题发生一般不针对性处理,而是直接修改程序。
public class Error {public static void main(String[] args) {byte b = 128; // 128超出了byte的范围}} /* Output:Exception in thread "main" java.lang.Error: Unresolved compilation problem:Type mismatch: cannot convert from int to byteat Error.main(Error.java:3)*///:~
Exception是可以被处理的,这是我们关心的基类型,异常可以分为两大类。 Exception和其子类都是,除了特殊子类RuntimeException体系。Exception中的RuntimeException和其子类。
public static void main(String[] args){Exception e = new Exception(); //仅创建了一个异常对象,并进行没有处理System.out.println(e);} /* Output:java.lang.Exception*///:~
当异常发生时,可以将这个异常对象通过throw关键字进行抛出,异常对象将从当前方法这一层到上一层(调用此方法的那一层),当抛出了异常之后就会退出当前作用域。所以在throw语句之后不能代码,否则会因为不能被执行而发生编译期错误。
public class Except {public static void main(String[] args) throws Exception { //声明异常Exception e = new Exception();throw e; //将异常对象抛出,异常对象将被JVM接收// ! System.out.println("不能被执行"); // Unreachable code}} /* Output:Exception in thread "main" java.lang.Exceptionat Except.main(Except.java:3)*///:~
Java提供的异常体系不可能预见所有的希望加以报告的错误,所以可以自己定义异常类来表示程序中可能会遇到的特定问题。
通常对异常来说,最重要的信息就是异常类型名。
错误信息可以保存在异常对象内部或者用异常类的名称来暗示,上一层环境通过这些信息来决定如何处理异常。
class MyException extends Exception { } // 异常类型名是此自定义异常类型仅有的信息public class Except {public static void show() throws MyException { // 声明异常MyException e = new MyException();throw e;}public static void main(String[] args) throws MyException { // 声明异常show();}} /* Output:Exception in thread "main" MyExceptionat Except.show(Except.java:5)at Except.main(Except.java:9)*///:~
class MyException extends Exception {public MyException(String message) {super(message); // 明确调用了基类的构造器,接受一个字符串作为参数。}}public class Except {public static void show() throws MyException { // 声明异常MyException e = new MyException("自定义类型");throw e;}public static void main(String[] args) { // 捕获异常try {show();} catch (MyException e) {e.printStackTrace();}}} /* Output:MyException: 自定义类型at Except.show(Except.java:12)at Except.main(Except.java:18)*///:~
对抛出的异常进行处理有两种方式:声明异常或捕获异常。
有一个很好的比喻来说明上面这句话,相信读者看完之后会有感触的。
有一个人带了两手雷准备坐飞机,你作为安检人员,发现这个人带了两手雷。throw new Exception("两个手雷");
throws Exceptioncatch(Exception e){}catch(Exception e){throw e;} & throws Exception通过使用
throws关键字在函数上对可能会抛出的异常类型进行声明。
public class Except {public static void show() throws Exception { // 声明异常Exception e = new Exception("声明异常");throw e; //抛出了异常,要对该异常有对应的预先处理方式}public static void main(String[] args) throws Exception { // 声明异常show();}} /* Output:Exception in thread "main" java.lang.Exception: 声明异常at Except.show(Except.java:3)at Except.main(Except.java:7)*///:~
throws使用在函数上(extends和implements用于类上),throw使用在函数内。throws抛出的是异常类,可以抛出多个,用逗号隔开,throw抛出的是异常对象。通过使用
catch关键字对抛出的异常进行捕获,从而可以进行下一步的处理。
public class Except {public static void show() throws Exception { // 声明异常Exception e = new Exception("声明异常");throw e;}public static void main(String[] args) { // 声明异常try {show();} catch (Exception e) { //捕获了异常System.out.println("捕获异常");}}} /* Output:捕获异常*///:~
要明白异常是如何被捕获的,必须首先理解监控区域的概念。它是一段可能产生异常的代码,并且后面跟着处理这些异常的代码。
try代码块在这个代码块中“尝试”各种可能产生异常的方法调用。
try {// Code that might generate exceptions}
catch代码块catch代码块也称为异常处理程序,派生异常类的对象可以匹配其基类的处理程序。
每一次“捕获”一种匹配的异常并进行相应的处理,必须在
try之后,可以有多个catch代码块(异常处理程序列表)。
try {// Code that might generate exceptions} catch (Type1 id1) {// Handle exceptions of Type1} catch (Type2 id2) {// Handle exceptions of Type2} catch (Type3 id3) {// Handle exceptions of Type3}
可以在处理程序的内部使用标识符(id1,id2等等),这与方法的形式参数的使用很相似。异常处理机制将负责把捕获的异常对象的类型与这些catch中的类型进行顺序匹配,当第一次匹配成功后,便进入catch子句执行,此时认为异常得到了处理,匹配结束,不会进行下一次匹配。
class MyException1 extends Exception { }class MyException2 extends Exception {public MyException2(String message) {super(message);}}public class Except {public static void show(int flag) throws MyException1, MyException2 {if (flag == 1) {throw new MyException1();}if (flag == 2) {MyException2 e = new MyException2("自定义类型");throw e;}}public static void main(String[] args) { // 声明异常try {show(2);} catch (MyException1 e) {e.printStackTrace();} catch (MyException2 e) { // 匹配成功e.printStackTrace(System.out); // 将异常输出到标准输出流中,即打印到主控台。} catch (Exception e) { // 父类异常必须在子类异常的后面!e.printStackTrace(System.out);}}} /* Output:MyException2: 自定义类型at Except.show(Except.java:15)at Except.main(Except.java:22)*///:~
多catch时,父类异常的catch放在最下面,否则在捕获子类异常时会编译失败。
编译器报错信息:“Unreachable catch block for xxException. It is already handled by the catch block for Exception”
通过捕获异常类型的基类Exception就可以捕获所有异常。必须放在处理程序列表的末尾,以防它抢在其他处理程序之前先把异常给捕获了。
finally代码块无论
try代码块中的异常是否抛出,都会被执行到。
try {// The guarded region: Dangerous activities// that might throw A, B or C} catch (A a1) {// Handler for situation A} catch (B b2) {// Handler for situation B} catch (C c3) {// Handler for situation C} finally {// Activities that happen every time}
为了证明finally子句总能运行,可以试试下面这个程序:
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.out.println("ThreeException");} finally {System.out.println("In finally clause");if (count == 2)break; // out of "while"}}}} /* Output:ThreeExceptionIn finally clauseNo exceptionIn finally clause*///:~
要把除内存之外的资源恢复到它们的初始状态时,就要用到
finally语句。
举个简单的例子,一般出门之前要把房间里所有的灯都关掉,可是你有时候出门会忘记关灯,这就造成了资源的浪费。所以无论怎么样都应该关掉灯,这时,这个关灯的动作可以放在finally代码块中。
class OnOffException1 extends Exception { }class OnOffException2 extends Exception { }class Switch {private boolean state = false;public void on() {state = true;System.out.println(this);}public void off() {state = false;System.out.println(this);}public String toString() {return state ? "on" : "off";}}public class Final {private static Switch sw = new Switch();public static void f() throws OnOffException1, OnOffException2 { }public static void main(String[] args) throws OnOffException1, OnOffException2 {try {sw.on();f(); // Code that can throw exceptions..} finally {sw.off(); // 当异常发生时,我们无法处理,只能向上抛出,但是我们必须要关闭资源}}} /* Output:onoff*///:~
在
return中使用finally,即使执行到return,finally中的代码仍然会被执行。
public class MultipleReturns {public static void f(int i) {System.out.println("Initialization that requires cleanup");try {System.out.println("Point 1");if (i == 1)return;System.out.println("Point 2");if (i == 2)return;System.out.println("End");return;} finally {System.out.println("Performing cleanup"); // 总是会被执行的}}public static void main(String[] args) {for (int i = 1; i <= 3; i++)f(i);}} /* Output:Initialization that requires cleanupPoint 1Performing cleanupInitialization that requires cleanupPoint 1Point 2Performing cleanupInitialization that requires cleanupPoint 1Point 2EndPerforming cleanup*///:~
如果使用了退出虚拟机"
System.exit(0);",finally代码块不执行。
public class Exit {public static void main(String[] args) {try {System.out.println("start");// return是回到上一层,而System.exit(status)是回到最上层System.exit(0); // 正常退出程序System.out.println("---"); // 不会有报错,但是不会被执行} finally {System.out.println("exit"); // 不会执行!}}} /* Output:start*///:~
如果try或者catch语句里有return,那么代码的行为如下:
jsr指令跳到finally语句里执行;finally语句后: finally里都有return时,会忽略try和catch语句的return;finally里没有return,则返回之前保存在局部变量表里的值。当覆盖方法的时候,子类声明的异常必须是父类声明的异常或异常的导出类型。
其实上面这段话很容易理解,Java之所以这样做,其实是为了保证对象的可替换性。
在多态的情况下,一个后期绑定的方法声明throws了会抛出异常,在子类对象使用该方法的时候一旦抛出了异常,异常一定为子类所定义的。而在编译期对异常的处理都是以父类中该方法声明的抛出异常做出预先的处理方式,如果子类抛出的异常比父类的异常大或者为其他异常,那么将无法处理该异常。此时既无法声明异常又无法捕获异常,这种情况是编译器所不允许的。
通过查看API发现Exception类型没有自己的方法,都是从其父类Throwable继承过来的方法。这里将介绍一下以上并没有出现的方法。
public class Except {public static void show() throws Exception {throw new Exception("fillInStackTrace()方法");}public static void main(String[] args) throws Exception {try {show();} catch (Exception e) {// throw e;throw (Exception) e.fillInStackTrace(); // 变成了异常的新发生地}}} /* Output:Exception in thread "main" java.lang.Exception: fillInStackTrace()方法at Except.main(Except.java:11)*///:~
class MyException extends Exception {public MyException(String message) {super(message);}}public class Except {public static void show() throws Exception {MyException e = new MyException("包装异常");throw new Exception(e); //包装异常//throw (Exception)new Exception().initCause(new MyException("包装异常")); // 等价于上面两句,构造器包装异常更为常用}public static void main(String[] args){try {show();} catch (Exception e) {System.out.println(e.getCause());}}} /* Output:MyException: 包装异常*///:~
通过重抛异常的方式,把“被检查的异常”包装进
RuntimeException里面。
try {// ... to do something useful} catch (IDontKnowWhatToDoWithThisCheckedException e) {throw new RuntimeException(e);}
这些被包装的异常就成为了异常的cause,可以通过getCause()方法获取被包装的那个原始异常。