自定义异常
/*
* 自定义异常
* 在实际开发中,有时候需要些自定义异常,也就是Exception体系中没有的异常,来解决一些特殊的问题?
* 如何创建自定义异常?
* 1:创建一个类继承Exception或者RuntimeException
* 1.1:继承Exception会让我们的异常类变为编译时异常
* 1.2:继承RuntimeException会让我们的异常类变为运行时时异常
* 2:提供无参和有参的构造器
* 如何使用自定义异常?
*/
public class Test {
public static void main(String[] args) {
//1:创建学生对象
Student stu = new Student();
//2:初始化学生
stu.setName(\"宝强\");
try {
stu.setAge(2000);
} catch (AgeException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try {
stu.setSex(\"人妖\");
} catch (SexException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
public class Student {
private String name;
private int age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) throws AgeException {
if(age>=18 && age<=30){
this.age = age;
}else{
//System.out.println(\"年龄不符合范围 18~30\");
//throw new Exception(\"年龄不符合范围 18~30\");
throw new AgeException(\"年龄不符合范围 18~30\");
}
}
public String getSex() {
return sex;
}
public void setSex(String sex) throws SexException{
if(\"女\".equals(sex)||\"男\".equals(sex)){
this.sex = sex;
}else{
throw new SexException(\"性别只能是 男 or 女\");
//throw new Exception(\"性别只能是 男 or 女\");
//System.out.println(\"性别只能是 男 or 女\");
}
}
public Student(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public Student() {
super();
}
}
public class SexException extends RuntimeException {
public SexException(){
super();
}
public SexException(String message){
super(message);
}
}
public class AgeException extends Exception {
public AgeException(String message){
super(message);
}
public AgeException(){
super();
}
}
继续阅读与本文标签相同的文章
上一篇 :
视频云2017-12新功能更新
下一篇 :
机器学习2017年重大进展汇总
-
这3大医疗咨询APP开发优势,你了解吗?
2026-05-18栏目: 教程
-
众创空间WeWork暂停中国扩张:大中华区已是第三大市场
2026-05-18栏目: 教程
-
创建人物百科,怎么创建人物百科词条?
2026-05-18栏目: 教程
-
传统制造业牵手人工智能 开启智慧鞍山建设新时代
2026-05-18栏目: 教程
-
详解安检违禁品识别设计方案
2026-05-18栏目: 教程
