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的异常");
        }
    }
}
相关推荐
立心者023 分钟前
SpringBoot中使用TOTP实现MFA(多因素认证)
java·spring boot·后端
枕星而眠30 分钟前
C++ STL Map容器完全指南:从有序红黑树到无序哈希表
java·开发语言
爱吃牛肉的大老虎1 小时前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
bbq粉刷匠2 小时前
HashMap 底层原理深度拆解(二):putVal 完整链路解析(懒加载 · 链表遍历 · 尾插法)
java·开发语言·哈希算法
Sam_Deep_Thinking2 小时前
一个靠谱的C端网关服务应该包含什么内容
java·程序员·系统架构
@三十一Y2 小时前
C++:红黑树的实现
开发语言·c++
杨运交2 小时前
[055][调度模块]Spring动态任务调度框架的设计与实现
java·后端·spring
白狐_7982 小时前
408 数据结构算法题 01:线性表暴力求解保分指南
java·数据结构·算法
流云鹤3 小时前
03Java学习day(3)
java·学习
乐观勇敢坚强的老彭3 小时前
C++信奥:开关门、开关灯问题
开发语言·c++·算法