Java抛出异常有3种形式:
- throws
- throw
- 系统抛出异常
系统抛出异常
当程序语句出现一些逻辑错误,或类型转换错误时,系统会自动抛出异常
public static void main(String[] args) {int a = 5, b =0;System.out.println(5/b); // 此处系统会自动抛出ArithmeticException异常//function();}
throw
throw是语句抛出一个异常,一般是在代码块的内部,当程序出现逻辑错误时,由程序员主动抛出某种特定类型的异常。
public static void main(String[] args) {String s = "abc";if(s.equals("abc")) {throw new NumberFormatException();} else {System.out.println(s);}//function();}
运行时,系统会抛出如下异常:
Exception in thread "main" java.lang.NumberFormatException at......
throws
当某个方法可能会抛出某个异常时,用throws声明可能抛出的异常,然后交给上层调用它的function处理。
public class testThrows(){public static void function() throws NumberFormatException {String s = "abc";System.out.println(Double.parseDouble(s));}public static void main(String[] args) {try {function();} catch (NumberFormatException e) {System.err.println("非数据类型不能强制类型转换。");//e.printStackTrace();}}
运行结果:
非数据类型不能强制类型转换。
throw与throws比较:
- throws出现在函数头;throw出现在函数体;
- throws表示出现异常的一种可能性,并不一定会发生这个异常;throw则是抛出了异常,执行throw一定是抛出了某种异常对象;
- 两者都是消极处理异常的方式,只是抛出或者可能抛出异常,但是不会由这个函数去处理异常,真正处理这个异常的是函数的上层调用者。
编程习惯
- 写程序时,对可能出现异常的部分用try{…}catch{…}捕捉并进行处理;
- 用try{…}catch{…}捕捉到异常后,一定要处理,打log,或者e.printStackTrace();
- 如果是捕捉到IO输入输出流的异常,一定要在try{…}catch{…}后加finally{…},把输入输出流关闭;
- 如果在函数体内用throw抛出了某种异常,最好在函数名中加throws抛异常声明,然后交给调用它的上层函数处理。
