第六次实训作业异常处理
- 编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
- 在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
- 在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
- 在finally语句块中,输出一条语句。
- 代码为:
-
import java.util.Scanner; public class ExceptionTest { int a; int b; public static void main(String[] args) { ExceptionTest a1 = new ExceptionTest(); Scanner rd=new Scanner(System.in); System.out.print("请输入第一个数"); a1.a=rd.nextInt(); System.out.print("请输入第二个数"); a1.b=rd.nextInt(); try{ int c=a1.a/a1.b; }catch(ArithmeticException e){ e.printStackTrace(); } finally{ System.out.print("除数不能为零"); } }
- 编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。
代码为:
import java.util.Scanner; public class round { double r; public static void main(String[] args){ round a1=new round(); Scanner rd=new Scanner(System.in); try{ System.out.print("请输入半径"); a1.r=rd.nextDouble(); double s=a1.r*a1.r*3.14; System.out.println("圆的面积为"+s); }catch(Exception e){ } finally{ System.out.println("请输入正确的半径"); Scanner re=new Scanner(System.in); a1.r=re.nextDouble(); double s=a1.r*a1.r*3.14; System.out.print("圆的面积为"+s); } } }
- 为类的属性“身份证号码.id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能。
代码为:
package class5; import java.io.IOException; import java.util.Scanner; public class id { String id; String idd; static void pop(String idd,String id) throws IOException { int n=idd.length(); if(n==18) { id=idd; System.out.println("输入正确"); } } public static void main(String[] args) { id a1=new id(); Scanner rd=new Scanner(System.in); System.out.println("请输入身份证信息:"); a1.idd=rd.next(); try { pop(a1.idd,a1.id); }catch(IOException e) { System.out.println(e.getMessage()); } finally { System.out.println("身份证信息输入错误"); } } }