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的异常");
        }
    }
}
相关推荐
粉032114 分钟前
Keeppalived 实现Nginx 的高可用集群
java·服务器·nginx
水瓶丫头站住16 分钟前
Qt中QRadioButton的样式设置
开发语言·qt
路在脚下@31 分钟前
Java使用Redisson实现布隆过滤器
java·spring boot
魔道不误砍柴功1 小时前
Java中的Stream API:从入门到实战
java·windows·python
晚安7201 小时前
idea添加web工程
java·前端·intellij-idea
xinghuitunan1 小时前
时间转换(acwing)c/c++/java/python
java·c语言·c++·python
八月五1 小时前
Java并发编程——ThreadLocal
java·并发编程
多敲代码防脱发2 小时前
Spring框架基本使用(Maven详解)
java·网络·后端·spring·maven