无名商城论坛

搜索
查看: 300|回复: 0

[其他技术] 【LSP】Java异常(三)

[复制链接]

1万

主题

1万

帖子

3万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
32464
发表于 2022-5-8 17:04:20 | 显示全部楼层 |阅读模式


五、 自定义异常如何自定义异常类?继承于现有的异常结构:RuntimeException 、Exception提供全局常量:serialVersionUID提供重载的构造器public class MyException extends Exception{                static final long serialVersionUID = -7034897193246939L;                public MyException(){                        }                public MyException(String msg){                super(msg);        }}此时使用自己定义的异常类package com.atguigu.java2;public class StudentTest {                public static void main(String[] args) {                try {                        Student s = new Student();                        s.regist(-1001);                        System.out.println(s);                } catch (Exception e) {//                        e.printStackTrace();                        System.out.println(e.getMessage());                }        }        }class Student{                private int id;                public void regist(int id) throws Exception {                if(id > 0){                        this.id = id;                }else{                        throw new MyException("不能输入负数");                }        }        @Override        public String toString() {                return "Student [id=" + id + "]";        }                }6|0六、问题进入A----用A方法----制造异常----进入方法B-----调用B

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表