java第五次實訓做業異常處理

1.編寫一個類ExceptionTest,在main方法中使用try-catch-finally語句結構實現:
 在try語句塊中,編寫兩個數相除操做,相除的兩個操做數要求程序運行時用戶輸入;
 在catch語句塊中,捕獲被0除所產生的異常,並輸出異常信息;
 在finally語句塊中,輸出一條語句。java

 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異常,而後捕獲和處理異常,編寫程序實現以上功能。this

 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  }
相關文章
相關標籤/搜索