第六次实训作业异常处理
- 编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
- 在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
- 在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
- 在finally语句块中,输出一条语句。
- 编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
- 在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
- 在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
- 在finally语句块中,输出一条语句。
1.package work;
import java.util.*;
public class ExceptionTest {
public static void main(String[] args){
Scanner A=new Scanner(System.in);
System.out.println("请输入两个数:");
int i=A.nextInt();
int j=A.nextInt();
try{
System.out.println("输出结果:"+i/j);
}
catch(ArithmeticException e){
System.out.println("除数不能为零!");
}
finally{
System.out.println("异常处理成功!");
}
}
}
2.编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。
2.package work;
import java.util.*;
public class round {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final double PI=3.14;
try{
Scanner A=new Scanner(System.in);
System.out.println("输入圆的半径:");
double r=A.nextDouble();
System.out.println("面积结果为:"+PI*r*r);
}
catch(InputMismatchException e){
e.printStackTrace();
System.out.println("输入类型不是double型");
}
finally{
System.out.println("异常处理结束!");
}
}
}
3.为类的属性“身份证号码.id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能。
3.package work;
import java.util.*;
public class identity {
/**
* @param args
*/
public static int count(String num)throws IllegalArgumentException{
int count=num.length();
String id;
if(count!=18){
System.out.println("身份证长度非18位");
}
else{
id=num;
System.out.println("赋值给id为:"+id);
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int id;
try{
Scanner A=new Scanner(System.in);
System.out.println("请输入身份证号码:");
String num=A.next();
count(num);
}
catch(IllegalArgumentException e){
e.printStackTrace();
System.out.printf("身份证长度不为18位");
}
finally{
System.out.println("异常处理结束");
}
}
}