异常Exception
1.异常分为运行时异常和检查异常
1.运行时异常 RuntimeException。
2.检查异常就是除了运行时异常以外的异常。
他们都继承了Exception
1.运行时异常可以不用处理,在运行的时候出现,JVM会自动抛出
2.而检查异常必须要处理,try catch 或 throws 关键字抛出异常,不然通不过编译
2.关于什么时候用 try{}catch{} 什么时候用 throws
- 首先,如果是在实例方法里的检查异常,他需要依赖main方法去调用它的时候,可以向外抛throws
- 如果是在其他地方调用这些抛出异常的方法进行执行的时候就可以,try{}catch{}进行捕获异常处理,方便对异常进行操作,和继续执行接下来的操作!
3.自定义异常
举个例子
1.先自定义一个异常类比如 :AgeException 你想继承 Exception 或RuntimeException 都行,只是前者需要处理,后者可以不需要处理
package com.qf.exception.Demo1;
public class AgeException extends Exception{
public AgeException(String message) {
super(message);
}
}
2.然后创建,一个实体类 ,比如Person 私有属性年龄 age ,在set方法里,设置必须大于0小于100 , 否则抛出异常,这里是别人调用自己的方法,所以可以向外抛,然后在里面先自定义 new 一个AgeException异常
package com.qf.exception.Demo1;
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) throws AgeException {
if (age>0&&age<100){
this.age = age;
}else {
throw new AgeException("你输入的年龄有问题");
}
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
3.测试类传年龄报错, try{}catch{}捕获异常。打印栈信息,以及打印传入构造方法的message 因为继承了父类Exception 他有自己的类方法,
public String getMessage();
package com.qf.exception.Demo1;
public class Test {
public static void main(String[] args) {
Person person = new Person();
person.setName("kuangshen");
try {
person.setAge(129);
} catch (AgeException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println(person);
}
}