第五次实验作业异常处理

1.编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
  在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
  在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
  在finally语句块中,输出一条语句。

@@问题:在这个程序中“Scanner sc=new Scanner(System.in)”出现了一点点小问题,虽然不影响结果运行,但是为什么会有Resource leak(资源泄露):‘sc’ is never closed  的这种问题。

package guweiyi;
import java.util.Scanner;
public class ExceptionText {
public static void main(String[]args) {
    Scanner sc=new Scanner(System.in);
    System.out.println("请输入被除数:");
    int p1=sc.nextInt();
    System.out.println("请输入除数:");
    int p2=sc.nextInt();
    int result=0;
    try {
        result=p1/p2;
    
}catch(ArithmeticException e) {
    e.printStackTrace();
}finally {
    System.out.println("异常处理");
    
}
    System.out.println(result);
}
}

2.编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。

package guweiyi;

import java.util.*;
public class Circle {
public static void main(String[]args) {
    double r;
    double s=0;
    Scanner sc=new Scanner (System.in);
    System.out.println("请输入圆的半径:");
    try {
        r=sc.nextDouble();
        s=r*r*3.14;
    }catch(InputMismatchException e){
        e.printStackTrace();
        System.out.println("输入类型异常");
    }finally {
        System.out.println("圆的面积为:"+s);
        System.out.println("PROGRAM OVER");
    }
}
}

3.为类的属性“身份证号码.id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能。

package guweiyi;
import java.util.Scanner;
public class IDText {
          static String id;         // 身份证号码的长度应为18 
public void LengthJudge (String id) throws 
 IllegalArgumentException{
    if (id.length() == 18) {  
             this.id = id;
            System.out.println("身份证号码长度正常");
}                                     //判断身份证号码的长度是否为18
      else{ 
           throw new IllegalArgumentException("身份证号码长度异常");                               //抛出异常 
    } 
} 
public static void main(String[] args) { 
      Scanner sc=new Scanner(System.in);
      IDText p1=new IDText();
try {
           System.out.println("请输入身份证号码:");
            p1.id=sc.next();
           p1.LengthJudge(p1.id);
} catch (IllegalArgumentException e) {
        System.out.println("异常");
        //捕获和处理异常
               System.out.println(ie.getMessage());
}finally{
            System.out.println("身份证号码为:"+id);
    } 
    }
}

猜你喜欢

转载自www.cnblogs.com/zhangyixing/p/10873116.html
今日推荐