throws关键字声明异常

throws

throws的作用是声明抛出异常,在方法声明的位置上使用throws关键字向上抛出异常。例如下面程序演示了一般性异常,编译无法通过,需要对异常进行处理


import java.io.FileInputStream;

public classExceptionTest{

    publicstaticvoidmain(String[] args){

        //这句代码的意思是创建文件输入流,读取文件,遇到不认识的类可以查看API        

FileInputStream fis = new FileInputStream("d:/jh.txt");

    }

}


可以使用throws将异常抛出


mport java.io.*;public classExceptionTest{

    publicstaticvoidmain(String[] args)throwsFileNotFoundException{

        //这句代码的意思是创建文件输入流,读取文件        FileInputStream fis = new FileInputStream("d:/jh.txt");

    }

}


jvm是怎么知道这个地方容易出现问题呢?来看下FileInputStream的源码


publicFileInputStream(String name)throwsFileNotFoundException{

    this(name != null ? new File(name) : null);

}


源码里面在构造方法上抛出了FileNotFoundException,所以jvm知道。

深入throws

其实使用throws抛出异常并不是真正的去处理异常,而是抛给其调用者去处理,比如你在工作中遇到问题了,交给了你的领导去解决,领导如果也不想解决就交给他的领导去解决。在上面程序里面,我们抛出了异常,最后是交给了jvm解决,jvm的解决方式就是将错误信息打印至控制台,然后关闭程序。

下面示例展示了将异常抛出的情况


import java.io.*;

public classExceptionTest04{

    publicstaticvoidmain(String[] args)throwsFileNotFoundException{

        //抛给调用者,如果都不进行处理的话,最终抛给了main方法        m1();

    }

    publicstaticvoidm1()throwsFileNotFoundException{

        m2();

    }

    publicstaticvoidm2()throwsFileNotFoundException{

        m3();

    }

    //向上抛出异常    publicstaticvoidm3()throwsFileNotFoundException{

        FileInputStream fis = new FileInputStream("c:/jh.txt");

    }

}


这里不是说使用throws是不好,使用throws主要意图是暴露问题,如何解决让调用者去决定

你可能感兴趣的:(throws关键字声明异常)