Java异常处理方式二

/*
 * 异常处理的方式二,在方法的声明处,显式的抛出该异常对象的类型
 * 格式:如:public static void method2() throws FileNotFoundException, IOException {}
 * 当在此方法内部出现异常的时候,会抛出一个异常类的对象,抛给方法的调用者
 * 异常的对象可以逐层向上抛,直至main中。当然在向上抛的过程中,可以再通过try-catch-finally进行处理。
 * 
 * java的异常处理,抓抛模型
 * 1.抓,异常的处理,有两种方式(1.try-catch-finally 2.throws + 异常的类型)
 * 2.抛,一旦执行过程中,出现异常,会抛出一个异常类的对象。(自动的抛出 vs 手动的抛出(throw new RuntimeException("传入的类型有误!");))
 *手动地抛出异常类型,若是RuntimeException,可以不显式地处理
 *若是一个Exception,必须要显式地处理
 */
class Circle{
    private double radius;

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    /**
     * @param radius
     */
    public Circle(double radius) {
        super();
        this.radius = radius;
    }
    //比较两个圆的半径大小
    public int CompareTo(Object obj) {
        if(this == obj) {
            return 0;
        }
        else if(obj instanceof Circle) {
            Circle c = (Circle)obj;
            if(this.radius > c.radius) {
                return 1;
            }else if(this.radius == c.radius){
                return 0;
            }else {
                return -1;
            }
            
        }
        else {
            //return -2;
            //手动地抛出一个异常
            throw new RuntimeException("传入的类型有误!");
        }
    }
}
public class TestException2 {
     public static void main(String[] args) {
         Circle c1 = new Circle(2.1);
         Circle c2 = new Circle(2.1);
         System.out.println(c1.CompareTo(c2));
         System.out.println(c1.CompareTo(new String("AA")));
         
        try {
            method2();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        method3();
    }
     public static void method3() {
         try {
            method1();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     }
     public static void method2() throws FileNotFoundException, IOException {
         method1();
     }
     public static void method1() throws FileNotFoundException,IOException{
         File file = new File("hello.txt");
         FileInputStream fis = new FileInputStream(file);
         int len;
         while((len = fis.read()) != -1) {
             System.out.println((char)len);
         }
         fis.close();
     }
}

 

猜你喜欢

转载自blog.csdn.net/weixin_41536380/article/details/88648871