子类重写的方法抛出的异常类型不大于父类重写的方法抛出的异常类型
开发中如何选择使用try-catch-finally还是用throws?
1、如果父类中被重写的方法没有throws的方式处理异常,则子类重写的方法也不能使用throws,意味着子类重写的方法中有异常,必须使用使用try-catch-finally的形式进行处理。
2、throws的方式只是将异常抛给了方法的调用者。并没有真正的将异常处理掉
3、如果父类被重写的方法中没有throws方式处理异常,则子类重写的方法也不能使用throws,意味着子类重写的方法中有异常,必须使用try-catch-finally方式处理
4、执行的方法a中,另外调用了几个方法,这几个方法是递进方式执行的。建议这几个方法使用throws的方式进行处理。而执行的方法a可以考虑用try-catch-finally的方式处理
关于异常对象的产生:
1、系统自动生成的异常对象
2、手动生成一个异常对象并抛出(throw)
public class StudentTest {
public static void main(String[] args) {
Student s = new Student();
try {
s.regist(-1001);
} catch (Exception e) {
// TODO 自动生成的 catch 块
// e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
class Student {
private int id;
public void regist(int id) throws Exception {
if (id > 0) {
this.id = id;
} else {
// System.out.println("您输入的数据非法!");
// 手动抛出异常对象
throw new Exception("您输入的数据非法!");
}
}
}