/**
* 自定义异常
*/
public class Test05 {
class IllegalAgeException extends Exception{
//非法年龄异常类 继承异常类
public IllegalAgeException(){
//无参构造器
public IllegalAgeException(String message){
//message中放异常的信息/描述
super(message);
//调用父类的有参构造器 构造器不能继承 不写时默认第一行super()调用无参构造器
class IllegalNameException extends Exception{
public IllegalNameException(){
public IllegalNameException(String message){
super(message);
class Adult{
String name;
int age;
public void setAge(int age){
if (age<19){
try {
throw new IllegalAgeException(\"年龄需满18周岁\");
//对数值进行限制 当这里抛出新的异常对象时 checked exception提示将这个异常进行try/catch处理或者Add exception to method signature 向方法签名添加异常
catch (IllegalAgeException e) {
//try尝试抛出 new IllegalAgeException catch这个new的exception用IllegalAgeException引用变量e指向 并且执行{抛出new运行时异常
throw new RuntimeException(e);
this.age = age;
public void setName(String str) throws IllegalNameException{
//对方法内的new异常 通过throws抛出
if (str==\"\"){
throw new IllegalNameException(\"需要输入有效字符\");
name = str;
public static void main(String[
args) {
Adult a = new Adult();
a.setAge(-1);
/*
Exception in thread \"main\" java.lang.RuntimeException: IllegalAgeException: 年龄需满18周岁
at Adult.setAge(Test05.java:27)
at Adult.main(Test05.java:35)
Caused by: IllegalAgeException: 年龄需满18周岁
at Adult.setAge(Test05.java:24)
... 1 more
Process finished with exit code 1
程序通过了编译 但在运行(Test05.java:35行)时throw异常 属于运行时异常 : 冒号后是异常的信息 在setAge()方法内抛出的IllegalAge异常已被catch处理 但(Test05.java:27行)new Runtime异常叫停了进程
throw new RuntimeException(e); 将IllegalAge异常对象e传参进 RuntimeException()构造方法中
new Runtime异常的原因Caused by IllegalAge异常: 异常的信息
在(Test05.java:24行) throw new IllegalAgeException(\"年龄需满18周岁\");
*/
try {
a.setName(\"\");
//checked exception提示处理非法命名异常
catch (IllegalNameException e) {
e.printStackTrace();
//打印栈跟踪信息
System.exit(-1);
//系统退出返回-1异常退出
/*
IllegalNameException: 需要输入有效字符
at Adult.setName(Test05.java:43)
at Adult.main(Test05.java:66)
Process finished with exit code -1
异常类:信息
(Test05.java:43) throw new IllegalNameException(\"需要输入有效字符\");
(Test05.java:66) a.setName(\"\");
这里的异常退出是手动在catch{语句块中添加的 没有这一项的话进程会在catch异常后继续往下运行至结束
*/
【AMD|java自定义异常】
- 液晶显示器|2022年7月Steam硬件调查报告:AMD处理器份额大幅度上升
- 锐龙|AMD锐龙7000处理器首次公开PCIe 5.0硬盘性能 有点不给力
- 摩托罗拉|5nm Zen 4来了!AMD锐龙7000处理器首发型号及价格曝光
- 华为鸿蒙系统|AMD准备超级便宜的APU:CPU+GPU黄金组合 跑分诡异
- 高通骁龙|AMD RDNA 3 GPU 和 APU 出现在 Linux 补丁中
- AMD|AMD锐龙7 5700X体验:便宜好用的八核游戏芯
- AMD|iPhone14Max全新渲染图,到底升级了什么?iPhone13还香吗?
- radeon|AMD Radeon RX 6700 型号开始销售
- 苹果|AMD新处理器太猛!锐龙5 7600X爆锤Intel旗舰,单核性能超强
- 英特尔|AMD赢麻了!市值反超英特尔,连12代酷睿也不能力挽狂澜?