码迷,mamicode.com
首页 > 其他好文 > 详细

自定义异常基本用法

时间:2018-01-07 23:27:01      阅读:326      评论:0      收藏:0      [点我收藏+]

标签:except   打印   not   out   string   bsp   new   end   sage   

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

自定义异常基本用法

标签:except   打印   not   out   string   bsp   new   end   sage   

原文地址:https://www.cnblogs.com/zhangjianbing/p/8232593.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!