java第五次实训作业异常处理

1.编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
 在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
 在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
 在finally语句块中,输出一条语句。

 1 package LHB.inherit; 
 2 import java.util.*;
 3 public class ExceptionTest
 4 {
 5 
 6  public static void main(String[] args)
 7  {     
 8      try  
 9      {   
10          Scanner in=new Scanner(System.in); 
11          int x,y,z;
12          System.out.print("请输入两个数:");
13          x=in.nextInt(); 
14          y=in.nextInt();   
15          z=x/y; 
16          System.out.print("结果是:");
17          System.out.println(z); 
18          }     
19      catch(ArithmeticException e)     
20      {     
21          e.printStackTrace();   
22      }  
23      finally 
24      {   
25          System.out.println(6666); 
26      } 
27      }
28 
29 }

2.编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。

 1 package LHB.Demo;
 2  import java.util.*;
 3  public class Area 
 4 {
 5  public static void main(String[] args) 
 6  {  
 7  try  
 8  {   
 9  Scanner in=new Scanner(System.in);
10     double s,r;  
11   System.out.print("请输入圆的半径:");
12     r=in.nextDouble();  
13     s=r*r*3.14;  
14   System.out.println("圆的面积是:"+s);  
15  }  
16  catch(InputMismatchException e) 
17   {  
18   e.printStackTrace(); 
19   }   
20  }
21 }

3.为类的属性“身份证号码.id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能。

 1 package LHB.inherit;
 2   class Person 
 3   {
 4      private String name;
 5      private int age;
 6      private String id;
 7      public String getId() 
 8      {
 9          return id;
10      }
11      public void setId(String id) throws IllegalArgumentException
12      {
13          if(id.length()!=18)
14          {
15              throw(new IllegalArgumentException());
16          }
17          this.id = id;
18      }
19  }
20   class IllegalArgumentException extends Exception
21   {
22   }
23 
24  public class ExceptionTest1 {
25  
26      public static void main(String[] args) 
27      {
28          Person p1 = new Person();
29          Person p2 = new Person();
30          try 
31          {
32              p1.setId("430223200010031111");
33              p2.setId("43654576345");
34          } 
35          catch (IllegalArgumentException e) 
36          {
37              System.out.println("你输入的身份证长度有错误");
38          }
39  
40      }
41  
42  }

 

posted @ 2019-05-16 14:01  sky灬刘海波  阅读(608)  评论(0编辑  收藏  举报