目录
一、什么是异常
程序在运行时发生了错误,这便是异常;
它表示了程序发生了意外情况,并向调用者传递调用信息;
程序出现异常时,程序便会停止。
二、常见异常
异常名 | 说明 |
---|---|
ArithmeticException | 计算错误 |
NullPointerException | 空指针 |
ClassCastException | 类型转换异常 |
ClassNotFoundException | 找不到类 |
ArrayIndexOutOfBoundsException | 数组下标越界 |
三、异常捕获
try {
//代码块
} catch (异常对象) {
//异常处理
}finally {
//异常出口
}
对一个异常进行捕获;
try {
//代码块
} catch (异常对象) {
//异常处理
}catch(异常对象){
//异常处理
}finally {
//异常出口
}
对多个异常进行捕获;
代码演示:
try {
Scanner scanner = new Scanner(System.in);
int cs = scanner.nextInt();
} catch (InputMismatchException c) {
System.out.println("输入类型错误");
} catch (Exception e) {
System.out.println("未知错误");
}finally {
System.out.println("结束");
}