文章目录
1. 一览表

2. 测试题-下面的测试输出什么
分析:
- 首先,会在 main 方法中执行 methodA() ,进入到 methodA() 方法后,执行 try 里面的语句 输出:进入方法A
 - 由于有 finally ,所以就会执行 finally 后面的语句:用A方法的finally,再执行上面的 try 里面的语句,此时 throw 抛出了 
RuntimeException("制造异常"),就会被 main 方法中的 catch 捕获,就会打印出异常信息e.getMessage(),由于throw加入了抛出的信息,就会输出:制造异常 - 接着执行 methodB() 方法,进入到 try 后输出:进入方法B,return 并不会马上被执行,finally 会优先执行,输出:调用B方法的finally,最后再执行 return 结束。



 
3. 捕获多种异常情况
a) 编写应用程序EcmDef.java,接收命令行的两个参数(整数),计算两数相除。
 b) 计算两个数相除,要求使用方法 cal(int n1, int n2)
 c) 对数据格式不正确(NumberformatException)、缺少命令行参数
 (ArraylndexOutOfBoundsException)、除O进行异常处理(ArithmeticException)
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]);
            double res = cal(n1, n2);//该方法可能抛出ArithmeticException
            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的异常");
        }
    }
    //编写cal方法,就是两个数的商
    public static double cal(int n1, int n2) {
        return n1 / n2;
    }
}
 
-  
输入正确的参数



 -  
输入错误的参数情况




 -  
输入 0 的情况


 
4. 练习1

public class Homework02 {
    public static void main(String[] args) {
        //args.length = 0
        //这里发生的是 ArrayIndexOutOfBoundsException
        if(args[4].equals("john")){  //可能发生NullPointerException
            System.out.println("AA");
        }else{
            System.out.println("BB");
        }
        Object o= args[2]; //String->Object ,向上转型
        Integer i = (Integer)o; //错误,这里一定会发生 ClassCastException
    }
}
 

- 配置五个参数后


 
5. 练习2

public class Homework03 {
    public static void func() {//静态方法
        try {
            throw new RuntimeException();
        } finally {
            System.out.println("B");
        }
    }
    public static void main(String[] args) {//main方法
        try {
            func();
            System.out.println("A");
        } catch (Exception e) {
            System.out.println("C");
        }
        System.out.println("D");
    }
}
 

6. 练习3

public class Homework04 {
    public static void main(String[] args) {//main方法
        try {
            showExce();
            System.out.println("A");
        } catch (Exception e) {
            System.out.println("B");
        } finally {
            System.out.println("C");
        }
        System.out.println("D");
    }
    public static void showExce() throws Exception {
        throw new Exception();
    }
}
 











