官方文档API

异常

Throwable 类 实现了 序列化接口

Error

(错误:物理性的,JVM 虚拟机本身的问题,程序指令处理不了)

StackOverflowError
OutOfMemoryError

Exception

(异常:人为规定的不正常的现象)

  • 运行时异常

    Error、RuntimeException

javac 编译时,不会发现和提示

NegativeArraySizeException // 数组长度负数
NullPointerException // 空指针
ArithmeticException // 数字异常
ClassCastException // 造型异常
IllegalArgumentException // 非法参数
IndexOutOfBoundsException // 集合越界
StringIndexOutOfBoundsException // 字符串
NumberFormatException // 数字格式化
ArrayIndexOutOfBoundsException // 数组索引越界
  • 编译时异常

    除了 Error、RuntimeException 以外的其他异常
    javac 编译的时候 强制要求我们必须处理 (try throws)

InterruptedException

处理异常方式

try catch finally

1
2
3
4
5
6
7
8
9
10
11
12
13
14
try{
Thread.sleep(5000);
return "a";
}catch(异常类型 e){

}catch(异常类型 e){
e.printStackTrace();
}
catch(Exception e){

}finally{
//必须执行
}
return "a";
try catch finally
catch 可以存在多个,捕获异常之间不能有继承关系,由小到大进行捕获
不管 return 关键字在哪里,finally 一定会执行完毕
返回值的具体结果,根据执行过程决定

final:修饰符
finally:异常捕获的一部分
finalize:Object 类中的一个 protected 方法,对象没有任何引用的时候,垃圾回收时默认调用的方法

throws

异常只能在方法上抛出

1
2
3
4
5
6
public String myException() throws NullPointerException,NumberFormatException(){
String s = null;
s.length();
}

//方法在哪里被调用,哪里抛出异常,方法可以抛出多个异常

自定义异常

自定义类 extends RuntimeException –> 运行时异常
自定义类 extends Exception –> 编译时异常

throw 抛出异常

1
2
3
4
5
6
7
8
9
public String myException extends RuntimeException(){
public myException();
public myException(String msg){
super(msg);
};
}

//如何使用
throw new myException();