Java自定义异常处理

快捷键 ctrl+alt+t ,ctrl+h查看类的继承关系

异常的使用方式
1. 捕获
try{
逻辑代码
}catch(异常类名 e){
获取异常信息
}catch(异常类名 e){
获取异常信息
}…
finally{
总被执行…
}

    Exception 包含运行异常+非运行异常
    如果有多个catch ,Exception只能放到最后1个catch

2. 抛出 throws 异常类名

自定义异常

  1. 自定义类 继承 Exception

  2. 如果要想查看异常信息 ,一般会 提供构造函数

  3. 如果想丰富 自定义异常类, 可以将加入 异常出错 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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值