当前位置: 代码迷 >> J2SE >> FileNotFoundException 下
  详细解决方案

FileNotFoundException 下

热度:597   发布时间:2016-04-24 01:34:50.0
FileNotFoundException 请教大家下
public FileInputStream(String name)
  throws FileNotFoundException


throws FileNotFoundException 为什么throws FileNotFoundException 要用try catch语句对啊,throws不是向上一级抛出异常吗?不过他不是runtime Exception 必须要捕获,不然会出错的。

------解决方案--------------------
你应该是要问为什么在方法上面抛出了 FileNotFoundException 异常,但在方法体中还要用try catch吧,我的理解是在方法体中你还要抛出其它的异常,而你抛出 FileNotFoundException 只抛出了文件找不到这个异常,没有抛出其它的异常,如果你用public FileInputStream(String name) throws Exception那么在方法体中就不用再写try catch了。这里主要涉及到一个异常的范围(大小)的问题
------解决方案--------------------
上一级就是指调用这方法的那条语句 由于这方法有可能会抛出异常 所以你在调用该方法时就必须尝试着去捕获他
------解决方案--------------------
有运行呀,我把代码copy到我本机上,运行结果为(不想截图,就直接复制了结果):
而文件不错
-1
又成功了加油
输出了0个字符
------解决方案--------------------
while((b = fis.read()) != 0) {

改为while((b = fis.read()) != -1) {

read
public int read()
throws IOException
Reads a byte of data from this input stream. This method blocks if no input is yet available. 

Specified by:
read in class InputStream
Returns:
the next byte of data, or -1 if the end of the file is reached. 
Throws: 
IOException - if an I/O error occurs.
------解决方案--------------------
完全不懂你要问什么,你的代码中之所以要catch异常是因为你的方法体是没有异常抛出的,但是你方法体内部却是有异常的。所有才需要try catch。如果你的方法体声明成:
public static void main(String args[])throws FileNotFoundException..这样就不用try catch了
------解决方案--------------------
探讨

完全不懂你要问什么,你的代码中之所以要catch异常是因为你的方法体是没有异常抛出的,但是你方法体内部却是有异常的。所有才需要try catch。如果你的方法体声明成:
public static void main(String args[])throws FileNotFoundException..这样就不用try catch了
  相关解决方案