Java异常处理之throws抛出异常

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java异常处理之throws抛出异常相关的知识,希望对你有一定的参考价值。

package com.test;

import java.io.FileReader;

public class Test2 {
    
    public static void main(String[] args) throws Exception
    {
        
        Father father = new Father();
        father.test1();
        father.test2();
    }

}

class Father{
    
    private Son son = null;
    
    public Father()
    {
        this.son = new Son();
    }
    
    public void test1()
    {
        System.out.println("1");
        //要调son的test2必须要捕获或者抛出一层层往上抛,最终抛给虚拟机
        
        try {
            son.test2();
            
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("把一个异常交给上一层调用者去处理");
            System.out.println("父亲在处理");
            e.printStackTrace();
        }
    }
    //或者都不管一层层向上 throws,一层层向上抛,跑到main函数最终抛给JVM虚拟机
    public void test2() throws Exception
    {
        System.out.println("1");
        //要调son的test2必须要捕获或者抛出一层层往上抛,最终抛给虚拟机
        
        son.test2();
    }
}

class Son{
    
    public void test2() throws Exception
    {
        FileReader fr = null;
        fr = new FileReader("D:\\aa.txt");
    }
}

 

以上是关于Java异常处理之throws抛出异常的主要内容,如果未能解决你的问题,请参考以下文章