- 编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
- 在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
- 在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
- 在finally语句块中,输出一条语句。
import java.util.*; public class Exception{ public static void main(String[] args) { int x,y,s; Scanner a=new Scanner(System.in); x=a.nextInt(); y=a.nextInt(); try{ s=x/y; System.out.println(s); } catch(ArithmeticException e){ System.out.println("除数不能为零!"); } finally{ System.out.println("运算结束!"); } } }
运行结果:
- 编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。
import java.util.*; public class jisuan { static final double PI=3.14; public static void main(String[] args) { double r,s; try{ Scanner a=new Scanner(System.in); r=a.nextDouble(); s=PI*r*r; System.out.println(s); } catch(InputMismatchException e){ System.out.println("输入的数必须为DOUBLE型!"); } finally{ System.out.println("计算结束!"); } } }
运行结果:
3.为类的属性“身份证号码.id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能
import java.util.*; class IllegalArgumentException extends Exception{ public IllegalArgumentException(){ super("身份证号错误!"); } } public class idcard { public static void main(String[] args) { String id; try{ Scanner a=new Scanner(System.in); id=a.nextLine(); int length=id.length(); if(length!=18){ throw new IllegalArgumentException(); } System.out.println("身份证号正确"); }catch(IllegalArgumentException e){ System.out.println(e.getMessage()); } finally{ System.out.println("运算结束!"); } } }