学习视频:https://www.imooc.com/learn/110
一.异常介绍
1.Java异常分类
Throwable
Error(出现程序彻底崩溃)
VirtualMachineError(虚拟机错误)
ThreadDeath(线程死锁)
Excpetion(编码/环境/用户操作输入出现问题)
RuntimeException(运行时异常,非检查异常)由java虚拟机自动抛出,基本是代码逻辑上的问题
NullPointerException(空指针异常)
ArrayIndexOutOfBoundsException(数组下标越界异常)
ClassCastException(类型转换异常)
ArithmeticExcption(算数异常)等等
CheckException(检查异常)需要手动添加捕获和处理语句
IOException(文件异常)
SQLException(SQL异常)
二、异常处理
1.捕获方法:try-catch语句块
tips:当程序抛出异常时,会就行寻找异常处理程序,所以在进行异常处理时,父类要在子类之后
2.抛出异常
当该异常不能处理时,将异常抛出给上一层的程序进行异常处理。
3.自定义异常
必须继承于意思相近的异常或者是基类的exception类:class 自定义异常类 extends 异常类型{}
4.异常链
自定义异常类
public class DrunkException extends Exception {
public DrunkException(){
}
public DrunkException(String message){
super(message);
}
}
public static void main(String[] args) {
ChainTest ct = new ChainTest();
try{
ct.test2();
}catch(Exception e){
e.printStackTrace();
}
}
public void test1() throws DrunkException{
throw new DrunkException("喝车别开酒!");
}
public void test2(){
try {
test1();
} catch (DrunkException e) {
// TODO Auto-generated catch block
RuntimeException newExc =
new RuntimeException(e);
// newExc.initCause(e);
throw newExc;
}
}