1.编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
在finally语句块中,输出一条语句。
程序如下:
1 package Exception; 2 import java.util.Scanner; 3 public class ExceptionTest 4 { 5 public static void main(String[] args) 6 { 7 Scanner sc=new Scanner(System.in); 8 try 9 { 10 System.out.println("请输入两个数:"); 11 int x=sc.nextInt(); 12 int y=sc.nextInt(); 13 int z=x/y; 14 System.out.println("这两个数相除结果为:"+z); 15 16 } 17 catch(ArithmeticException e) 18 { 19 20 e.printStackTrace(); 21 } 22 finally 23 { 24 System.out.println("程序运行结束!"); 25 } 26 sc.close(); 27 28 } 29 }
运行结果为:
2.编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。
程序如下:
1 package Exception; 2 import java.util.*; 3 public class InputMismatchDemo 4 { 5 public static double Area(double r) 6 { 7 return r*r*Math.PI; 8 } 9 public static void main(String[] args) 10 { 11 Scanner sc=new Scanner(System.in); 12 try 13 { 14 System.out.println("请输入半径:"); 15 double r=sc.nextDouble(); 16 System.out.println("此圆的面积为:"+Area(r)); 17 } 18 catch(Exception e) 19 { 20 e.printStackTrace(); 21 } 22 sc.close(); 23 } 24 25 }
运行结果为:
3.为类的属性“身份证号码.id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能。
程序如下:
1 package Exception; 2 import java.util.*; 3 public class Person 4 { 5 String id; 6 public void LengthJudge(String id) throws IllegalArgumentException 7 { 8 9 if(id.length()>18||id.length()<18) 10 { 11 throw new IllegalArgumentException("身份证号码长度不合法!"); 12 } 13 else 14 { 15 System.out.println("长度合法!"); 16 } 17 18 } 19 public static void main(String[] args) 20 { 21 Scanner sc=new Scanner(System.in); 22 Person p=new Person(); 23 try 24 { 25 System.out.println("请输入身份证号码:"); 26 p.id=sc.next(); 27 p.LengthJudge(p.id); 28 29 } 30 catch(IllegalArgumentException e) 31 { 32 System.out.println(e); 33 } 34 sc.close(); 35 } 36 }
运行结果如下: