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的异常");
        }
    }
}
相关推荐
合作小小程序员小小店10 分钟前
web网页开发,在线考勤管理系统,基于Idea,html,css,vue,java,springboot,mysql
java·前端·vue.js·后端·intellij-idea·springboot
CoderYanger1 小时前
前端基础——CSS练习项目:百度热榜实现
开发语言·前端·css·百度·html·1024程序员节
虾..2 小时前
C++ 哈希
开发语言·c++·哈希算法
liu****2 小时前
14.日志封装和线程池封装
linux·开发语言·c++
青青草原羊村懒大王2 小时前
python基础知识三
开发语言·python
将编程培养成爱好2 小时前
C++ 设计模式《统计辅助功能》
开发语言·c++·设计模式·访问者模式
随便叫个啥呢2 小时前
java使用poi-tl模版+vform自定义表单生成word,使用LibreOffice导出为pdf
java·pdf·word
fie88892 小时前
基于循环谱分析的盲源分离信号处理MATLAB
开发语言·matlab·信号处理
kgduu2 小时前
go-ethereum之rpc
开发语言·rpc·golang
yong99903 小时前
MATLAB倍频转换效率分析与最佳匹配角模拟
开发语言·前端·matlab