Java 第13章 异常 本章作业

1 编程 两数相除的异常处理


各自属于哪些异常:

数据格式不正确 NumberformatException

缺少命令行参数 ArrayIndexOutOfBoundsException

除0异常处理 ArithmeticException

ArrayIndexOutOfBoundsException 为数组下标越界时会抛出的异常,可以在检测到命令行参数个数不等于2时,人为强制抛出该异常(要不然只有在取args[下标]的时候,才能发现出现异常),然后再在catch中进行处理:

java 复制代码
 if (!(args.length == 2))
 	throw new ArrayIndexOutOfBoundsException("参数个数不对");

throw和throws的区别:

throws表明本方法不负责处理,去找调用本方法的对象进行处理(踢皮球);

throw用于手动生成异常对象

* IDE中的命令行参数配置:

完整代码:

java 复制代码
public class Homework01 {
    public static int cal(int n1, int n2) {
        return n1 / n2;
    }
    public static void main(String[] args) {
        try {
            if (!(args.length == 2))
                throw new ArrayIndexOutOfBoundsException("参数个数不对");
            int n1 = Integer.parseInt(args[0]);
            int n2 = Integer.parseInt(args[1]);
            int res = cal(n1, n2);
            System.out.println("结果=" + res);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        } catch (NumberFormatException e) {
            System.out.println("格式不正确,需要输入整数");
        } catch (ArithmeticException e) {
            System.out.println("出现除以0的异常");
        }
    }
}
相关推荐
码农阿豪2 分钟前
远程调试不再难!Remote JVM Debug+cpolar 让内网 Java 程序调试变简单
java·开发语言·jvm
lubiii_5 分钟前
MCP应用:cursor+hexstrike-ai的安全实战
开发语言·web安全·ai·php
stillaliveQEJ6 分钟前
【JavaEE】Spring AOP(二)
java·spring·java-ee
是罐装可乐8 分钟前
前端架构知识体系:深入理解 sessionStorage、opener 与浏览器会话模型
开发语言·前端·javascript·promise·语法糖
cd ~/Homestead9 分钟前
PHP 变量、类型、运算符
android·开发语言·php
何中应12 分钟前
在Coze上新建一个插件
开发语言·python·ai
岁岁种桃花儿13 分钟前
Spring Boot项目核心配置:parent父项目详解(附实操指南)
java·spring boot·spring
YYHPLA16 分钟前
【无标题】
java·spring boot·后端·缓存
木易 士心18 分钟前
加密与编码算法全解:从原理到精通(Java & JS 实战版)
java·javascript·算法
专注于大数据技术栈18 分钟前
java学习--ArrayList
java·学习