自定义异常基本用法

1.定义异常类

  - 可以继承Exception(编译时异常)

  - 也可以继承RuntimeException(运行时异常)

  这两个有什么区别?

  粗俗讲,编译时异常必须在编程阶段处理,比如FileNotFoundException异常,而运行时异常不需要在编码时处理比如NullPointException

public class CustomException extends Exception {

    // 自定义异常无参构造方法
    public CustomException() {}
    
    // 自定义异常有参构造方法:参数String类型,为的是getMessage方法
    public CustomException(String msg) {
        super(msg);
    }
    // =====基本用法就是以上:两个构造方法=====
    
}

2.模拟用户登录代码

在这里因为继承的是Exception所以这个异常必须处理,下面代码不能够使用try catch进行处理,必须向上抛,谁调用这个方法就抛给谁,在测试主方法中进行捕捉处理

public class UserLogin {

    // 模拟用户登录的方法
    // 用户名必须大于6位
    public void login(String name) throws CustomException {
        if (name.length() < 6) {
            // 手动抛异常
            throw new CustomException("用户名长度不能小于6位!");
        }
        System.out.println("用户名合法!");
    }

}

3.测试main方法

若发证异常,就捕捉,输出打印自定义的异常

public class Test {
    public static void main(String[] args) {
        try {
            UserLogin login = new UserLogin();
            login.login("zhang");
        } catch (CustomException e) {
            System.out.println(e.getMessage());
        }
    }
}

 

QQ交流群:4060038

posted @ 2018-01-07 22:22  在谷歌上百度  阅读(231)  评论(0编辑  收藏  举报