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的异常");
        }
    }
}
相关推荐
货拉拉技术11 分钟前
网关 MCP 转换技术:从实现到平台落地
java·架构·mcp
艾菜籽12 分钟前
SpringMVC练习:加法计算器与登录
java·spring boot·spring·mvc
啊森要自信13 分钟前
【GUI自动化测试】Python 自动化测试框架 pytest 全面指南:基础语法、核心特性(参数化 / Fixture)及项目实操
开发语言·python·ui·单元测试·pytest
赵谨言24 分钟前
基于python智能家居环境质量分析系统的设计与实现
开发语言·经验分享·python·智能家居
元亓亓亓36 分钟前
考研408--组成原理--day1
开发语言·javascript·考研·计组
Yurko1343 分钟前
【C语言】环境安装(图文)与介绍
c语言·开发语言·学习
浮游本尊44 分钟前
Java学习第25天 - Spring Cloud Alibaba微服务生态
java
仲星(._.)44 分钟前
C语言:字符函数和字符串函数
c语言·开发语言
kyle~1 小时前
C++---向上取整
开发语言·c++
Cg136269159741 小时前
Super的详解
java