1.1、异常的基本概念
什么是异常,在程序运行过程中出现的错误,称为异常
public class ExceptionTest01 {public static void main(String[] args) {int i1 = 100;int i2 = 0;int i3 = i1/i2;System.out.println(i3);}}
没有正确输出,抛出了被0除异常
通过以上示例,我们看到java给我们提供了这样一个体系结构,当出现问题的时候,它会告诉我们,并且把错误的详细信息也告诉我们了,这就是异常的体系结构,这样我们的程序更健壮,我们可以把这个信息,再进行处理以下告诉用户。从上面大家还可以看到,java异常都是类,在异常对象中会携带一些信息给我们,我们可以通过这个异常对象把信息取出来
public class ExceptionTest01 {public static void main(String[] args) {StringBuffer sbf = new StringBuffer();for(long i=0;i<Long.MAX_VALUE;i++){sbf.append("T-"+i);}}}堆空间溢出--------------------------------------------Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
public class ExceptionTest02 {public static void main(String[] args) {main(args);}}栈空间溢出--------------------------------------------Exception in thread "main" java.lang.StackOverflowErrorat com.test.ExceptionTest02.main(ExceptionTest02.java:5)
public class ExceptionTest05 {public static void main(String[] args) throws IOException {BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));String line = bf.readLine();System.out.println(line);bf.close();}}
1.2、异常的分类
1 .2.1、异常的层次结构
1.2.2、异常的分类
异常主要分为:错误、编译时异常、运行时异常
- 错误:如果应用程序出现了Error,那么将无法恢复,只能重新启动应用程序,最典型的Error的异常是:OutOfMemoryError、StackOverflowError
 - 编译时异常:出现了这种异常必须显示的处理,不显示处理java程序将无法编译通过
 - 运行时异常:此种异常可以不用显示的处理,例如被0除异常,java没有要求我们一定要处理
1.2.3、try、catch和finally
异常的捕获和处理需要采用try和catch来处理,具体格式如下: ```java try { 
}catch(OneException e) {
}catch(TwoException e) {
}finally {
}
- try中包含了可能产生异常的代码- try后面是catch,catch可以有一个或多个,catch中是需要捕获的异常- 当try中的代码出现异常时,出现异常下面的代码不会执行,马上会跳转到相应的catch语句块中,如果没有异常不会跳转到catch中- finally表示,不管是出现异常,还是没有出现异常,finally里的代码都执行,finally和catch可以分开使用,但finally必须和try一块使用,如下格式使用finally也是正确的```javatry {}finally {}
public class ExceptionTest02 {public static void main(String[] args) {int i1 = 100;int i2 = 0;//try里是出现异常的代码//不出现异常的代码最好不要放到try作用try {//当出现被0除异常,程序流程会执行到“catch(ArithmeticException ae)”语句//被0除表达式以下的语句永远不会执行int i3 = i1/i2;//永远不会执行System.out.println(i3);//采用catch可以拦截异常//ae代表了一个ArithmeticException类型的局部变量//采用ae主要是来接收java异常体系给我们new的ArithmeticException对象//采用ae可以拿到更详细的异常信息}catch(ArithmeticException ae) {System.out.println("被0除了");}}}
1.2.4、getMessage和printStackTrace()
如何取得异常对象的具体信息,常用的方法主要有两种:
- 取得异常描述信息:getMessage()
 取得异常的堆栈信息(比较适合于程序调试阶段):printStackTrace();
public class ExceptionTest03 {public static void main(String[] args) {int i1 = 100;int i2 = 0;try {int i3 = i1/i2;System.out.println(i3);}catch(ArithmeticException ae) {//ae是一个引用,它指向了堆中的ArithmeticException//通过getMessage可以得到异常的描述信息System.out.println(ae.getMessage());}}}
public class ExceptionTest04 {public static void main(String[] args) {method1();}private static void method1() {method2();}private static void method2() {int i1 = 100;int i2 = 0;try {int i3 = i1/i2;System.out.println(i3);}catch(ArithmeticException ae) {//ae是一个引用,它指向了堆中的ArithmeticException//通过printStackTrace可以打印栈结构ae.printStackTrace();}}}
1.2.5、编译时异常
```java import java.io.FileInputStream;
public class ExceptionTest05 {
public static void main(String[] args) {FileInputStream fis = new FileInputStream("test.txt");}
}
从上面输出可以看到,无法编译,它抛出了一个异常,这个异常叫做“编译时市场”FileNotFoundException,也就是说在调用的时候必须处理文件不能找到<br />处理FileNotFoundException```java/*import java.io.FileInputStream;import java.io.FileNotFoundException;*/import java.io.*;public class ExceptionTest06 {public static void main(String[] args) {try {FileInputStream fis = new FileInputStream("test.txt");}catch(FileNotFoundException ffe) { //此异常为编译时异常,必须处理ffe.printStackTrace();}}}
1.2.6、finally关键字
finally在任何情况下都会执行,通常在finally里关闭资源
import java.io.*;public class ExceptionTest07 {public static void main(String[] args) {try {FileInputStream fis = new FileInputStream("test.txt");System.out.println("-------before fis.close--------");//close是需要拦截IOException异常//在此位置关闭存在问题,当出现异常//那么会执行到catch语句,以下fis.close永远不会执行//这样个对象永远不会得到释放,所以必须提供一种机制//当出现任何问题,都会释放相应的资源(恢复到最初状态)//那么就要使用finally语句块fis.close();System.out.println("-------after fis.close--------");}catch(FileNotFoundException e) {e.printStackTrace();}catch(IOException e) {e.printStackTrace();}}}
采用finally来释放资源
import java.io.*;public class ExceptionTest08 {public static void main(String[] args) {//因为fis的作用域问题,必须放到try语句块外,局部变量必须给初始值//因为是对象赋值为nullFileInputStream fis = null;try {//FileInputStream fis = new FileInputStream("test.txt");fis = new FileInputStream("test.txt");/*System.out.println("-------before fis.close--------");fis.close();System.out.println("-------after fis.close--------");*/}catch(FileNotFoundException e) {e.printStackTrace();}finally {try {System.out.println("-------before fis.close--------");//放到finally中的语句,程序出现任何问题都会被执行//所以finally中一般放置一些需要及时释放的资源fis.close();System.out.println("-------after fis.close--------");}catch(IOException e) {e.printStackTrace();}}}}
深入finally
public class ExceptionTest09 {public static void main(String[] args) {int i1 = 100;int i2 = 10;try {int i3 = i1/i2;System.out.println(i3);return;}catch(ArithmeticException ae) {ae.printStackTrace();}finally {//会执行finallySystem.out.println("----------finally---------");}}}
public class ExceptionTest10 {public static void main(String[] args) {int i1 = 100;int i2 = 10;try {int i3 = i1/i2;System.out.println(i3);//return;System.exit(-1); //java虚拟机退出}catch(ArithmeticException ae) {ae.printStackTrace();}finally {//只有java虚拟机退出不会执行finally//其他任何情况下都会执行finallySystem.out.println("----------finally---------");}}}
public class ExceptionTest11 {public static void main(String[] args) {int r = method1();//输出为:10System.out.println(r);}/*private static int method1(){byte byte0 = 10;byte byte3 = byte0; //将原始值进行了保存byte byte1 = 100;return byte3;Exception exception;exception;byte byte2 = 100;throw exception;}*/private static int method1() {int a = 10;try {return a;}finally {a = 100;}}}
public class ExceptionTest12 {public static void main(String[] args) {int r = method1();//输出为:100System.out.println(r);}/*private static int method1(){byte byte0 = 10;byte0 = 50;byte0 = 100;break MISSING_BLOCK_LABEL_18;Exception exception;exception;byte0 = 100;throw exception;return byte0;}*/private static int method1() {int a = 10;try {a = 50;}finally {a = 100;}return a;}}
1.2.7、final、finalize和finally?
finalize()是Object里面的一个方法,当一个堆空间中的对象没有被栈空间变量指向的时候,这个对象会等待被java回收
可以通过:System.gc();//手动调用垃圾回收 去测试这个finalize
1.2.8、如何声明异常
在方法定义处采用throws声明异常,如果声明的异常为编译时异常,那么调用方法必须处理此异常
import java.io.*;public class ExceptionTest13 {public static void main(String[] args)//throws FileNotFoundException, IOException { //可以在此声明异常,这样就交给java虚拟机处理了,不建议这样使用throws Exception { //可以采用此种方式声明异常,因为Exception是两个异常的父类/*//分别处理各个异常try {readFile();}catch(FileNotFoundException e) {e.printStackTrace();}catch(IOException e) {e.printStackTrace();}*///可以采用如下方式处理异常//因为Exception是FileNotFoundException和IOException的父类//但是一般不建议采用如下方案处理异常,粒度太粗了,异常信息//不明确/*try {readFile();}catch(Exception e) {e.printStackTrace();}*/readFile();}private static void readFile()throws FileNotFoundException,IOException { //声明异常,声明后调用者必须处理FileInputStream fis = null;try {fis = new FileInputStream("test.txt");//}catch(FileNotFoundException e) {// e.printStackTrace();}finally {//try {fis.close();//}catch(IOException e) {// e.printStackTrace();//}}}}
public class ExceptionTest14 {public static void main(String[] args) {//不需要使用try...catch..,因为声明的是运行时异常//method1();//也可以拦截运行时异常try {method1();}catch(ArithmeticException e) {e.printStackTrace();}}//可以声明运行时异常private static void method1() throws ArithmeticException {int i1 = 100;int i2 = 0;// try {int i3 = i1/i2;System.out.println(i3);/*}catch(ArithmeticException ae) {ae.printStackTrace();}*/}}
1.2.10、如何手动抛出异常
public class ExceptionTest15 {public static void main(String[] args) {int ret = method1(1000, 10);if (ret == -1) {System.out.println("除数为0");}if (ret == -2) {System.out.println("被除数必须为1~100之间的数据");}if (ret == 1) {System.out.println("正确");}//此种方式的异常处理,完全依赖于程序的返回//另外异常处理和程序逻辑混在一起,不好管理//异常是非常,程序语句应该具有一套完成的异常处理体系}private static int method1(int value1, int value2){if (value2 == 0) {return -1;}if (!(value1 >0 && value1<=100)) {return -2;}int value3 = value1/value2;System.out.println("value3=" + value3);return 1;}}
采用异常来处理参数非法
public class ExceptionTest16 {public static void main(String[] args) {//int ret = method1(10, 2);//System.out.println(ret);/*try {int ret = method1(1000, 10);System.out.println(ret);}catch(IllegalArgumentException iae) {//ide为指向堆中的IllegalArgumentException对象的地址System.out.println(iae.getMessage());}*/try {int ret = method1(1000, 10);System.out.println(ret);}catch(Exception iae) { //可以采用Exception拦截所有的异常System.out.println(iae.getMessage());}}private static int method1(int value1, int value2){if (value2 == 0) {////手动抛出异常throw new IllegalArgumentException("除数为0");}if (!(value1 >0 && value1<=100)) {//手动抛出异常throw new IllegalArgumentException("被除数必须为1~100之间的数据");}int value3 = value1/value2;return value3;}}
throws和throw的区别?thorws是声明异常,throw是抛出异常
进一步了解throw
public class ExceptionTest17 {public static void main(String[] args) {try {int ret = method1(1000, 10);System.out.println(ret);}catch(Exception iae) {System.out.println(iae.getMessage());}}private static int method1(int value1, int value2){try {if (value2 == 0) {////手动抛出异常throw new IllegalArgumentException("除数为0");//加入如下语句编译出错,throw相当于return语句//System.out.println("----------test111-----------");}if (!(value1 >0 && value1<=100)) {//手动抛出异常throw new IllegalArgumentException("被除数必须为1~100之间的数据");}int value3 = value1/value2;return value3;}finally {//throw虽然类似return语句,但finally会执行的System.out.println("-----------finally------------");}}}
1.2.11、异常的捕获顺序
异常的捕获顺序应该是:从小到大
import java.io.*;public class ExceptionTest18 {public static void main(String[] args) {try {FileInputStream fis = new FileInputStream("test.txt");fis.close();}catch(IOException e) {e.printStackTrace();}catch(FileNotFoundException e) {e.printStackTrace();}//将IOException放到前面,会出现编译问题//因为IOException是FileNotFoundException的父类,//所以截获了IOException异常后,IOException的子异常//都不会执行到,所以再次截获FileNotFoundException没有任何意义//异常的截获一般按照由小到大的顺序,也就是先截获子异常,再截获父异常}}
1.3、如何自定义异常
自定义异常通常继承于Exception或RuntimeException。如果需要调用方显示处理,则定义编译时异常,如果不需要对方显示处理,可以定义运行时异常。
import java.io.*;public class ExceptionTest19 {public static void main(String[] args) {try {method1(10, 0);}catch(MyException e) {//必须拦截,拦截后必须给出处理,如果不给出处理,就属于吃掉了该异常//系统将不给出任何提示,使程序的调试非常困难System.out.println(e.getMessage());}}private static void method1(int value1, int value2)throws MyException { //如果是编译时异常必须声明if (value2 == 0) {throw new MyException("除数为0");}int value3 = value1 / value2;System.out.println(value3);}}//自定义编译时异常class MyException extends Exception {public MyException() {//调用父类的默认构造函数super();}public MyException(String message) {//手动调用父类的构造方法super(message);}}
import java.io.*;public class ExceptionTest20 {public static void main(String[] args) {method1(10, 0);}private static void method1(int value1, int value2)//throws MyException {if (value2 == 0) {//抛出编译时异常,方法可以不适用throws进行声明//但也也可以显示的声明throw new MyException("除数为0");}int value3 = value1 / value2;System.out.println(value3);}}//自定义运行时异常class MyException extends RuntimeException {public MyException() {//调用父类的默认构造函数super();}public MyException(String message) {//手动调用父类的构造方法super(message);}}
1.4、方法覆盖与异常
方法覆盖的条件:
- 子类方法不能抛出比父类方法更多[大]的异常,但可以抛出父类方法异常的子异常 ```java import java.io.*;
 
public class ExceptionTest21 {
public static void main(String[] args) {}
}
interface UserManager {
public void login(String username, String password) throws UserNotFoundException;
}
class UserNotFoundException extends Exception {
}
class UserManagerImpl1 implements UserManager {
//正确public void login(String username, String password) throws UserNotFoundException {}
}
//class UserManagerImpl2 implements UserManager {
//不正确,因为UserManager接口没有要求抛出PasswordFailureException异常//子类异常不能超出父类的异常范围//public void login(String username, String password) throws UserNotFoundException, PasswordFailureException{//}
//}
class UserManagerImpl3 implements UserManager {
//正确,因为MyException是UserNotFoundException子类//MyException异常没有超出接口的要求public void login(String username, String password) throws UserNotFoundException, MyException {}
}
class PasswordFailureException extends Exception {
}
class MyException extends UserNotFoundException {
1.5、总结
- 异常的分类
 - 编译时异常和运行时异常
 - 异常的5个关键字try、catch、finally、throws、throw
 - 异常的捕获顺序,先捕获小的,再捕获大的
 - 自定义异常:
 
- 继承Exception,throw new的时候必须得throws抛出给调用者,相当于提示调用者必须捕获
 - 继承RuntimeExcetion,throw new的时候不是必须throws抛出给调用者
 - 建议:自定义异常尽量继承Exception,提示调用者必须处理异常,但是最终还是根据项目需求来
 
- 方法覆盖和异常的关系
 
.
