1. 编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
² 在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
² 在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
² 在finally语句块中,输出一条语句。
1 package demo; 2 3 import java.util.Scanner; 4 5 public class ExceptionTest { 6 7 public static void main (String[]args){ 8 try{ 9 int a,b; 10 Scanner in=new Scanner(System.in); 11 a=in.nextInt(); 12 b=in.nextInt(); 13 System.out.println(a/b); 14 }catch(ArithmeticException e){ 15 16 // e.printStackTrace(); 17 System.out.println("除数不能为零"); 18 19 } 20 finally{ 21 System.out.println("OK"); 22 } 23 } 24 25 }
2. 编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。
1 package demo; 2 3 import java.util.Scanner; 4 5 public class yuan { 6 public static void main (String[]args){ 7 final double PI = 3.1315; 8 double r,S; 9 Scanner in=new Scanner(System.in); 10 r = in.nextDouble(); 11 S = PI*r*r; 12 System.out.println(S); 13 } 14 }
1 package demo; 2 3 import java.util.Scanner; 4 5 import javax.rmi.CORBA.ClassDesc; 6 7 public class yuan { 8 public static void main (String[]args){ 9 try{ 10 final double PI = 3.1315; 11 double r,S; 12 Scanner in=new Scanner(System.in); 13 r = in.nextDouble(); 14 S = PI*r*r; 15 System.out.println(S); 16 }catch(Exception e){ 17 System.out.println("数据类型不匹配"); 18 } 19 } 20 }
3. 为类的属性“身份证号码.id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能。
1 package demo; 2 import java.util.*; 3 public class 异常 { 4 public static void ID (int size)throws IllegalArgumentException { 5 if(size!=18) 6 { 7 throw new IllegalArgumentException(); 8 } 9 } 10 public static void main(String[] args){ 11 Scanner in=new Scanner(System.in); 12 System.out.println("请输入身份证号:"); 13 String id=in.next(); 14 try{ 15 ID(id.length()); 16 System.out.println(id); 17 } 18 catch(Exception e){ 19 System.out.println("输入错误,长度不符合,请重试!"); 20 //e.printStackTrace(); 21 } 22 finally { 23 System.out.println("OK"); 24 } 25 } 26 }
第三题不会,不会自定义异常,对我来说,还是有难度的,但是,白敬亭的女人绝不认输!!!