Java异常处理之throws抛出异常

时间:2023-03-08 17:45:29
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");
}
}