异常
Java异常的理解:
在程序中异常的意思就是:在程序执行的过程中,出现的非正常的情况,最终导致jvm的非正常停止。异常本身就是一个类,产生异常就创建类对象并抛出了一个异常对象,Java处理异常的方式就是中断异常。需要注意的是异常指的并不是语法错误,语法错了,编译就不能通过,不会产生字节码文件,更不能运行。
常出现的异常
NullPointerException 空指针异常
ArithmeticException 算数计算异常,如除数为0的情况
ArrayIndexOutOfBoundsException 数组下标越界
ClassCastException 类型强转异常
IllegalArgumentException 参数非法
ClassNotFoundException 在编译时无法找到指定的类
BufferOverflowException 缓存溢出
try…catch…
- 注意点
- 一个try块可以对应多个catch块
- 对不关心的异常采用Expection去接收
- 先处理子类,再处理父类,子类异常要在父类异常前面
- 假设有ABC三个异常,若A发生异常,不会执行BC
- try块尽量避免嵌套
例:
public static void main(String[] args) {
int[] arr = {0};People p = null;
try {
arr[1] = 10;
int a = 1/0;
p.Fun();
}catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
catch (ArithmeticException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
public class People {
private String name;
private int sex;
public People(String name, int sex) {
this.name = name;
this.sex = sex;
}
public void Fun(){}
执行结果如下:
java.lang.ArrayIndexOutOfBoundsException: 1
at try_catch.test.main(test.java:43)
finally
- 注意点
- 一定会执行
- 如果try块里包含return,并且finally块也包含return,从finally块return退出
- 如果try块里包含System.exit(),并且finally块也包含System.exit(),从try块中System.exit()退出。
throw与throws
- throw是语句抛出的一个异常,一般是在代码块的内部,当程序出现某种逻辑错误时主动抛出某种特定类型的异常。
- throws是方法可能抛出异常的声明,当某个方法可能会抛出某种异常时,用throws声明可能抛出的异常,然后交给上层调用它的方法程序处理。
例:
public static void Fun(int[] arr){
arr[1] = 0;
throw new ArrayIndexOutOfBoundsException();
}
public static void main(String[] args) {
int[] arr = {0};
try {
Fun(arr);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void Fun(int[] arr) throws Exception{
arr[1] = 0;
}
public static void main(String[] args) throws Exception{
int[] arr = {0};
Fun(arr);
}
throw和throws的比较:
- 1.throws出现在函数头,而throw出现在函数体;
- 2.throws表示出现异常的一种可能性,并不一定会发生这些异常,throw则是抛出了异常。
- 3.throw是具体向外抛出异常的,抛出的是一个异常实例,throws声明了是哪种类型的异常,使它的调用者可以捕获这个异常。