异常

1.判断程序输出的结果   

 1 public class ReturnExceptionDemo {
 2     static void methodA() {
 3         try {
 4             System.out.println("进入方法A");
 5             throw new RuntimeException("制造异常");
 6         } finally {
 7             System.out.println("用A方法的finally");
 8         }
 9     }
10     static void methodB() {
11         try {
12             System.out.println("进入方法B");
13             return;
14         } finally {
15             System.out.println("调用B方法的finally");
16         }
17     }
18     public static void main(String[] args) {
19         try {
20             methodA();
21         } catch (Exception e) {
22             System.out.println(e.getMessage());
23         }
24         System.out.println("*********************************");
25         methodB();
26     }
27 }

进入方法A
用A方法的finally
制造异常
*********************************
进入方法B
调用B方法的finally

 2.综合练习:自定义异常/异常处理/main()方法的再理解                                              

 1 /*
 2  * 编写应用程序EcmDef.java,接收命令行的两个参数,要求不能输入负数,计算两数相除。
 3         对 数 据 类 型 不 一 致 (NumberFormatException) 、
 4         缺 少 命 令 行 参 数(ArrayIndexOutOfBoundsException、
 5         除0(ArithmeticException)及输入负数(EcDef 自定义的异常)进行异常处理。
 6     提示:
 7         (1)在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
 8         (2)在main()方法中使用异常处理语句进行异常处理。
 9         (3)在程序中,自定义对应输入负数的异常类(EcDef)。
10         (4)运行时接受参数 java EcmDef 20 10 //args[0]=“20” args[1]=“10”
11         (5)Interger类的static方法parseInt(String s)将s转换成对应的int值。
12         如:int a=Interger.parseInt(“314”); //a=314;
13  */
14 
15 public class EcmDef {
16     public static void main(String[] args) {
17         try{
18             int i = Integer.parseInt(args[0]);//从控制台输出输入的角标为0的参数
19             int j = Integer.parseInt(args[1]);
20             int result = ecm(i, j);
21             System.out.println(result);
22         }catch(NumberFormatException e){
23             System.out.println("数据类型不一致");
24         }catch(ArrayIndexOutOfBoundsException e){
25             System.out.println("缺少命令行参数");
26         }catch(ArithmeticException e){
27             System.out.println("除0");
28         }catch(Exception e){//处理手动抛出的异常
29             System.out.println(e.getMessage());
30         }
31     }
32     //继承自己定义的异常,
33     public static int ecm(int i, int j) throws Exception{//此时包含编译时异常,需要加上
34         if (i < 0 | j < 0) {
35             throw new EcDef("不能输入负数");
36         }
37         return i/j;
38         
39     }
40 }
41 *****************************************************
42 //自定义的异常
43 public class EcDef extends Exception {
44     static final long serialVersionUID = -703489719939L;
45     public EcDef(){
46         
47     }
48     public EcDef(String msg){
49         super(msg);
50     }
51 }

 

                                                                                              

 

posted @ 2022-04-12 16:19  默以思道  阅读(116)  评论(0)    收藏  举报