JAVA异常作业(Chapter12)

JAVA异常作业(Chapter12),第1张

第十二章作业

第十二章作业
  • 第十二章作业
    • 1.编程,使用try catch 处理异常
    • 2、3、4.读代码

1.编程,使用try catch 处理异常
package com.exception;

/**
 * @author whj
 * @version 1.0
 */
public class Homework01 {
    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]);
            System.out.println(cal(n1,n2));
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        } catch (NumberFormatException e){
            System.out.println("数字格式不正确。");
        }catch (ArithmeticException e){
            System.out.println("被除数不能是0。");
        }


    }
    public static int cal(int n1, int n2){
        return n1 / n2;
    }
}
2、3、4.读代码

运行异常:

  1. NullPointerException 空指针异常
  2. ArithmeticException 数学运算异常
  3. ArrayIndexOutOfBoundsException 数组下标越界异常
  4. ClassCastException 类型转换异常
  5. NumberFormatException 数字格式不正确异常[]

运行时finally的代码块一定会被执行。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/877759.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存