当前位置: 首页 > news >正文

#课后作业1:课件动手动脑及验证内容解答 - 20243867孙堃2405

一、AboutException.java示例运行与异常处理基础验证

  1. 代码示例(模拟)
    public class AboutException {
    public static void main(String[] args) {
    // 演示被0除异常
    int i = 1, j = 0, k;
    try {
    k = i / j; // 可能抛出ArithmeticException的代码
    } catch (ArithmeticException e) {
    // 异常处理逻辑
    System.out.println("捕获到被0除异常:" + e.getMessage());
    e.printStackTrace(); // 打印异常堆栈信息
    } finally {
    System.out.println("无论是否发生异常,finally块都会执行");
    }

     // 演示数组越界异常int[] arr = {1, 2, 3};try {System.out.println(arr[5]); // 数组下标越界,抛出ArrayIndexOutOfBoundsException} catch (ArrayIndexOutOfBoundsException e) {System.out.println("捕获到数组越界异常:" + e.getMessage());}
    

    }
    }

  2. 运行结果
    捕获到被0除异常:/ by zero
    java.lang.ArithmeticException: / by zero
    at AboutException.main(AboutException.java:6)
    无论是否发生异常,finally块都会执行
    捕获到数组越界异常:Index 5 out of bounds for length 3

  3. 验证结论

  • try块包裹可能发生异常的代码,当异常发生时,程序跳转到对应catch块执行处理逻辑;
  • printStackTrace()方法可打印异常传播路径(方法调用堆栈),getMessage()方法可获取异常的具体描述信息;
  • finally块无论是否发生异常,都会被执行,常用于资源释放等“善后”操作。

二、assert语句与AssertionError验证

  1. 代码示例
    import java.util.Arrays;
    import java.util.List;

public class TestAssert {
public static void main(String[] args) {
List ints = Arrays.asList(1, 2, 3);
int s = 0;
for (int n : ints) {
s += n;
}
assert s == 7; // 实际s=6,断言失败将抛出AssertionError
}
}

  1. 运行步骤与结果
  • 步骤1:默认关闭assert功能运行(直接用java TestAssert命令),程序无任何输出,断言未生效;
  • 步骤2:启用assert功能运行(命令:java -ea TestAssert),运行结果如下:
    Exception in thread "main" java.lang.AssertionError
    at TestAssert.main(TestAssert.java:10)
  1. 验证结论
  • AssertionError属于Error类的子类,是系统级错误,默认情况下JVM关闭assert功能;
  • 需通过JVM参数“-ea”(enable assertions)启用assert功能,断言条件不满足时才会抛出AssertionError。

三、整数与浮点数除以零差异验证(基于javap反汇编)

  1. 测试代码
    // 整数除以零(抛出异常)
    public class IntDivideByZero {
    public static void main(String[] args) {
    int i = 1, j = 0, k;
    k = i / j;
    }
    }

// 浮点数除以零(不抛出异常)
public class DoubleDivideByZero {
public static void main(String[] args) {
double d1 = 100, d2 = 0, result;
result = d1 / d2;
System.out.println("浮点数除以零:" + result);
}
}

  1. javap反汇编步骤与结果
  • 步骤1:编译代码(javac IntDivideByZero.java DoubleDivideByZero.java);
  • 步骤2:反汇编查看字节码(javap -c IntDivideByZero 与 javap -c DoubleDivideByZero);
  • 关键字节码差异:
    • IntDivideByZero的main方法中,整数除法对应“idiv”字节码指令;
    • DoubleDivideByZero的main方法中,浮点数除法对应“ddiv”字节码指令。
  1. 验证结论
  • JVM对“idiv”和“ddiv”指令采用不同处理策略:整数除以零违反数学逻辑,JVM抛出ArithmeticException;浮点数除以零在IEEE 754标准中定义为“Infinity”(无穷大),因此不抛出异常,直接返回该结果。

四、多层异常捕获验证(CatchWho.java与CatchWho2.java)

(一)CatchWho.java运行验证

  1. 代码示例(修正语法错误:ArrayIndex0utOfBoundsException应为ArrayIndexOutOfBoundsException)
    public class CatchWho {
    public static void main(String[] args) {
    try {
    try {
    throw new ArrayIndexOutOfBoundsException();
    } catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("ArrayIndexOutOfBoundsException/内层try-catch");
    }
    throw new ArithmeticException();
    } catch (ArithmeticException e) {
    System.out.println("发生ArithmeticException");
    } catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("ArrayIndexOutOfBoundsException/外层try-catch");
    }
    }
    }

  2. 运行结果
    ArrayIndexOutOfBoundsException/内层try-catch
    发生ArithmeticException

  3. 验证结论

  • 内层try块抛出的ArrayIndexOutOfBoundsException被内层catch块捕获并处理;
  • 内层异常处理完成后,外层try块继续执行“throw new ArithmeticException()”,该异常被外层对应catch块捕获。

(二)CatchWho2.java运行验证

  1. 代码示例(修正语法错误)
    public class CatchWho2 {
    public static void main(String[] args) {
    try {
    try {
    throw new ArrayIndexOutOfBoundsException();
    } catch (ArithmeticException e) { // 内层catch块类型与抛出异常不匹配
    System.out.println("ArrayIndexOutOfBoundsException/内层try-catch");
    }
    throw new ArithmeticException();
    } catch (ArithmeticException e) {
    System.out.println("发生ArithmeticException");
    } catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("ArrayIndexOutOfBoundsException/外层try-catch");
    }
    }
    }

  2. 运行结果
    ArrayIndexOutOfBoundsException/外层try-catch

  3. 验证结论

  • 内层try块抛出ArrayIndexOutOfBoundsException,但内层catch块声明捕获ArithmeticException,异常无法被内层处理,向外层传播;
  • 外层catch块中,ArrayIndexOutOfBoundsException对应的catch块在前(注:原代码中外层catch顺序为ArithmeticException在前,此处需注意:若外层先捕获ArithmeticException,ArrayIndexOutOfBoundsException仍会被后续catch块捕获),最终被外层对应catch块处理;
  • 内层未执行“throw new ArithmeticException()”,因此该异常未抛出。

五、finally执行时机与System.exit()影响验证(EmbedFinally.java与SystemExitAndFinally.java)

(一)EmbedFinally.java(多层嵌套finally)

  1. 代码示例
    public class EmbedFinally {
    public static void main(String[] args) {
    try { // 外层try
    System.out.println("进入外层try块");
    try { // 内层try
    System.out.println("进入内层try块");
    throw new ArithmeticException("内层异常"); // 抛出异常
    } catch (ArithmeticException e) {
    System.out.println("内层catch:" + e.getMessage());
    } finally {
    System.out.println("内层finally块执行");
    }
    } catch (Exception e) {
    System.out.println("外层catch块执行");
    } finally {
    System.out.println("外层finally块执行");
    }
    }
    }

  2. 运行结果
    进入外层try块
    进入内层try块
    内层catch:内层异常
    内层finally块执行
    外层finally块执行

  3. 验证结论

  • 多层嵌套finally时,执行顺序与嵌套顺序一致:先执行内层finally,再执行外层finally;
  • 无论异常在哪个层级抛出,只要被捕获,所有层级的finally都会执行。

(二)SystemExitAndFinally.java(System.exit()对finally的影响)

  1. 代码示例
    public class SystemExitAndFinally {
    public static void main(String[] args) {
    try {
    System.out.println("进入try块");
    System.exit(0); // 终止JVM运行
    } catch (Exception e) {
    System.out.println("catch块执行");
    } finally {
    System.out.println("finally块执行");
    }
    }
    }

  2. 运行结果
    进入try块

  3. 验证结论

  • finally块并非“绝对”执行:当执行System.exit(0)时,JVM直接终止,后续代码(包括finally块)不再执行;
  • System.exit(int status)用于强制终止JVM,status为0表示正常终止,非0表示异常终止。

六、Java 7 try-with-resources特性验证(自动释放资源)

  1. 代码示例(基于FileInputStream,需处理IOException)
    import java.io.FileInputStream;
    import java.io.IOException;

public class TryWithResourcesDemo {
public static void main(String[] args) {
// try-with-resources语法:括号内创建实现AutoCloseable接口的对象
try (FileInputStream fis = new FileInputStream("test.txt")) {
System.out.println("文件输入流创建成功,可进行读写操作");
// 模拟文件操作(此处省略具体读写逻辑)
} catch (IOException e) {
System.out.println("捕获IO异常:" + e.getMessage());
}
// 无需手动调用fis.close(),JVM自动调用
}
}

  1. 运行结果(分两种情况)
  • 情况1:test.txt文件存在,运行结果:
    文件输入流创建成功,可进行读写操作
  • 情况2:test.txt文件不存在,运行结果:
    捕获IO异常:test.txt (系统找不到指定的文件)
  1. 验证结论
  • try-with-resources语法要求括号内的对象必须实现AutoCloseable接口(FileInputStream实现了该接口);
  • 当程序离开try块(正常执行完成或发生异常)时,JVM会自动调用AutoCloseable接口的close()方法释放资源,无需在finally块中手动调用,避免资源泄露;
  • 若close()方法本身抛出异常,会被catch块捕获(与业务异常一并处理)。

七、受控异常(Checked Exception)验证(TestThrows.java)

  1. 原错误代码与编译报错
    public class TestThrows {
    public static void main(String[] args) {
    FileInputStream fis = new FileInputStream("a.txt"); // 编译报错
    }
    }
  • 编译报错原因:FileInputStream的构造方法声明抛出FileNotFoundException(受控异常),该异常属于直接派生自Exception的Checked Exception,必须显式处理(捕获或声明抛出),否则编译不通过。
  1. 修正代码1(声明抛出异常)
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;

public class TestThrows {
// main方法声明抛出FileNotFoundException,由JVM默认处理(打印异常信息并终止程序)
public static void main(String[] args) throws FileNotFoundException {
FileInputStream fis = new FileInputStream("a.txt");
}
}

  1. 修正代码2(捕获异常)
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;

public class TestThrows {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("a.txt");
} catch (FileNotFoundException e) {
System.out.println("捕获文件未找到异常:" + e.getMessage());
} catch (IOException e) { // FileNotFoundException是IOException的子类,需放在前面捕获
System.out.println("捕获IO异常:" + e.getMessage());
}
}
}

  1. 验证结论
  • 受控异常(Checked Exception)直接派生自Exception,必须显式处理:要么在方法上用throws声明抛出,由调用者处理;要么用try-catch捕获处理;
  • 捕获异常时,子类异常的catch块必须放在父类异常catch块之前(如FileNotFoundException的catch块需在IOException之前),否则编译报错(父类异常会“遮蔽”子类异常,子类异常的catch块无法执行)。

八、子类重写方法抛出受控异常的限制验证(OverrideThrows.java)

  1. 代码示例(父类与子类)
    import java.io.FileNotFoundException;
    import java.io.IOException;

// 父类
class Parent {
// 父类方法声明抛出IOException(受控异常)
public void readFile() throws IOException {
System.out.println("父类读取文件方法");
}
}

// 子类1(合法:抛出父类异常的子类)
class Child1 extends Parent {
@Override
public void readFile() throws FileNotFoundException { // FileNotFoundException是IOException的子类
System.out.println("子类1读取文件方法");
}
}

// 子类2(非法:抛出父类异常的父类,编译报错)
class Child2 extends Parent {
@Override
// 编译报错:子类方法抛出的异常不能是父类方法抛出异常的父类
public void readFile() throws Exception {
System.out.println("子类2读取文件方法");
}
}

  1. 编译结果
  • Child1编译通过:子类重写方法抛出的异常(FileNotFoundException)是父类方法抛出异常(IOException)的子类,符合规则;
  • Child2编译报错:子类重写方法抛出的异常(Exception)是父类方法抛出异常(IOException)的父类,违反“子类抛出受控异常不能超出父类异常范围”的规则。
  1. 验证结论
  • 子类重写父类方法时,若父类方法声明抛出受控异常,子类方法抛出的受控异常必须是父类异常的子类或相同异常,不能是父类异常的父类;
  • 子类方法可选择不抛出任何异常(即使父类方法抛出异常),但不能抛出比父类方法范围更广的受控异常。
http://www.jsqmd.com/news/30285/

相关文章:

  • 智变未来:中国AI HR市场进程盘点与主流玩家深度分析
  • PostgreSQL数据库:新手开启从0到1的学习之路
  • 2025电线电缆生产厂家,电线电缆厂家精选:武汉特航,赋能多行业的技术型品牌揭秘!
  • nfs 自动挂载的一些问题
  • 2025年浙江轻奶茶加盟渠道权威推荐榜单:奶茶加盟/茶饮加盟/奶茶店加盟渠道精选
  • 2025优质小型环保腻子粉,植物腻子粉,净醛腻子粉,健康腻子粉,无味腻子粉,腻子粉厂家推荐,实用选型参考
  • 2025年河南心理健康咨询机构权威推荐:河南婚姻心理咨询/河南家庭心理咨询/河南心理咨询机构服务中心精选
  • 面试:安全框架与安全管理-网络-防火墙与IPS - 徐正柱
  • 2025年汽车机油,润滑油厂家推荐榜:聚焦能源高端化发展潜力!
  • 2025小众嵌入式一体机,悬臂式一体机,ARM一体机,一体机厂家推荐榜:朗宇智能,聚焦细分场景的实力之选
  • 2025西南地区小型花卉大棚,单栋大棚,玻璃温室大棚,温室大棚厂家实用推荐:青程农业,适配中小种植户需求
  • 2025 年 11 月 DALI 调光系统厂家推荐排行榜,调光网关/调光开关/调光电源/调光驱动/调光传感器/调光模块/调光控制系统公司推荐
  • 2025 年热电偶厂家最新推荐排行榜:聚焦 K 型 / T 型 / 铠装丝 / 高温热电偶优质品牌
  • 2025年今日黄金回收价格机构权威推荐榜单:黄金上门回收/回收黄金机构/现在黄金回收价格源头机构精选
  • 2025年汽车音响生产厂家权威推荐榜单:车载音响/汽车音响喇叭/汽车音响功放源头厂家精选
  • 问问
  • 2025年北京合同纠纷律师事务所权威推荐榜:专业律师团队与高效解决方案口碑之选
  • SQL - JOIN 中关联条件和过滤条件的执行顺序
  • 解析国标GB28181算法算力平台EasyGBS视频分发与按需直播关键技术,实现海量视频的高效触达
  • 解析国标GB28181算法算力平台EasyGBS视频分发与按需直播关键技术,实现海量视频的高效触达
  • KubernetesClient-C
  • CSP-S 2025 Self Review -- Words to be remembered 2025.11.3
  • 2025年微型减速机工厂权威推荐榜单:蜗轮蜗杆减速机/小齿减速机/谐波减速机源头厂家精选
  • 2025 年同步时钟厂家最新推荐榜,聚焦技术实力与市场口碑深度解析,涵盖卫星北斗 GPS 授时安全领域授时安全/授时防护/信号安全/时空安全同步时钟公司推荐
  • 关于combinational and sequential parts of an fsm described in same always block ,spyglass警告
  • 2025年云南好的旅行社公司权威推荐榜单:云南青年旅行社/云南正规的旅行社/云南省十大旅行社源头公司精选
  • 记录一次数据恢复,mysql8 - 义美
  • 2025年新能源水冷电机壳铝合金浇铸机批发厂家权威推荐榜单:户外围墙配件铝合金浇铸机/厨具锅铝合金浇铸机/手套模具铝合金浇铸机源头厂家精选
  • 2025年耐高温的轴承制造商权威推荐榜单:轴承耐高温源头/高速耐高温轴承/耐高温高速轴承源头厂家精选
  • Chef:开源 AI 全栈应用构建工具实践