一.异常的分类
1.运行时的异常(程序员犯的错误 代码写错了 比如越界)
2.编译时的异常(除了运行时异常 全是编译时异常)
是为你可能发生的一场 进行一个准备
特点:系统强制你去处理这个异常
比如:读取文件时传入要读取的文件的路径 但是系统不知道你有没有这个文件
所以强制你处理(没有这个文件怎么办)
相当于 为可能发生的异常 提前做准备
exercise:
写一个类:
需求:计算圆的面积 并写出抛出运行时异常的方法 以及编译时异常的方法
class Test{
//抛编译时异常
public void bianYi() throws Exception {
throw new Exception("我是编译时异常");
}
//抛运行时异常
//当你这个方法的运行时异常时 方法上可以省略
//throws RunTimeException
public void yunXing() {
throw new RuntimeException("我是运行时异常");
}
public double getArea(int r) {
if (r <= 0) {
//半径小于零 再向下计算没有意义
//希望程序停下来 让程序员修改代码
//可以抛出一个运行时异常
throw new RuntimeException("你有病");
}
return 3.14 * r * r;
}
}
二.异常在继承中的问题
写一个父类一个子类
class Father{
//如果父类抛出了异常
//子类可以抛出异常 也可以try--catch处理
public void fun() {
}
}
子类重写父类的方法
class Son extends Father{
//重写父类方法
@Override
public void fun() {
//调用带异常的方法
//能不能把异常抛出去处理
//不能
//这时 只能用try--catch处理
try {
//当父类中的方法 没有抛出异常
//那么子类在重写父类这个方法的时候
//也不能抛出异常
method();
} catch (Exception e) {
// TODO: handle exception
}
}
//写一个抛出异常的方法
public void method() throws Exception {
throw new Exception();
}
}
当父类的方法没有抛出异常时 子类在重写父类这个方法的时候 也不能抛出异常
而当父类抛出了异常 子类可以抛出异常 也可以try -- catch来处理
练习1:
需求:无限输入正数 存放到集合中 打印 输入quit停止
(在输入字符串的时候 让程序也继续运行)
System.out.println("请输入整数");
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> arrayList = new ArrayList<>();
while (true) {
String string = scanner.nextLine();
if (string.equals("quit")) {
break;
}
//处理异常
try {
//字符串转整数
int num = Integer.parseInt(string);
//添加到集合
arrayList.add(num);
} catch (Exception e) {
System.out.println("看清楚要求再输入");
}
}
System.out.println(arrayList);