快捷键 ctrl+alt+t ,ctrl+h查看类的继承关系
异常的使用方式
1. 捕获
try{
逻辑代码
}catch(异常类名 e){
获取异常信息
}catch(异常类名 e){
获取异常信息
}…
finally{
总被执行…
}
Exception 包含运行异常+非运行异常
如果有多个catch ,Exception只能放到最后1个catch
2. 抛出 throws 异常类名
自定义异常
-
自定义类 继承 Exception
-
如果要想查看异常信息 ,一般会 提供构造函数
-
如果想丰富 自定义异常类, 可以将加入 异常出错 code , 将错误信息抽取成员变量
/**
-
异常入门
*/
public class ExceptionDemo {public static void main(String[] args) {
//快捷键 ctrl+alt+t ,ctrl+h查看类的继承关系 try { String str = "a"; System.out.println(Integer.parseInt(str)); System.out.println(str.charAt(1)); }catch(NumberFormatException e){ e.printStackTrace(); System.out.println("数据转换异常"+e.getMessage()); } catch (StringIndexOutOfBoundsException e) { e.printStackTrace(); System.out.println("字符串越界"+e.getMessage()); } catch (Exception e) { //捕获 漏掉的异常 e.printStackTrace(); }finally { System.out.println("总被执行"); }
}
}
/*
创建学生类
*/
public class Student {
private String id;
private String name;
private int age;
public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
/**
-
自定义异常类
*/
public class StudentException extends Exception {/**
- 通过构造函数获取异常信息
- @param message
*/
public StudentException(String message) {
super(message);
}
}
/*
下标越界
*/
public class StudentManagerImp implements StudentManager {
static int total = 2; //总人数
static int count = 0; //当前人数
Student[] stus = new Student[total];
@Override
public void add(Student stu) throws StudentException {
if (count < total) {
stus[count] = stu;
count++;
} else {
throw new StudentException("越界...");
}
}
public static void main(String[] args) {
StudentManagerImp sm = new StudentManagerImp();
Student s1 = new Student("01", "tom1", 21);
Student s2 = new Student("02", "tom2", 22);
Student s3 = new Student("03", "tom3", 23);
try {
sm.add(s1);
sm.add(s2);
sm.add(s3);
} catch (StudentException e) {
e.printStackTrace();
}
}
}
public interface StudentManager {
void add(Student stu)throws StudentException;
}